国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
CSDN技術(shù)中心 正則表達(dá)式
 

第一部分:
-----------------
正則表達(dá)式(REs)通常被錯(cuò)誤地認(rèn)為是只有少數(shù)人理解的一種神秘語言。在表面上它們確實(shí)看起來雜亂無章,如果你不知道它的語法,那么它的代碼在你眼里只是一堆文字垃圾而已。實(shí)際上,正則表達(dá)式是非常簡單并且可以被理解。讀完這篇文章后,你將會(huì)通曉正則表達(dá)式的通用語法。

支持多種平臺(tái)


正則表達(dá)式最早是由數(shù)學(xué)家Stephen Kleene于1956年提出,他是在對自然語言的遞增研究成果的基礎(chǔ)上提出來的。具有完整語法的正則表達(dá)式使用在字符的格式匹配方面上,后來被應(yīng)用到熔融信息技術(shù)領(lǐng)域。自從那時(shí)起,正則表達(dá)式經(jīng)過幾個(gè)時(shí)期的發(fā)展,現(xiàn)在的標(biāo)準(zhǔn)已經(jīng)被ISO(國際標(biāo)準(zhǔn)組織)批準(zhǔn)和被Open Group組織認(rèn)定。

正則表達(dá)式并非一門專用語言,但它可用于在一個(gè)文件或字符里查找和替代文本的一種標(biāo)準(zhǔn)。它具有兩種標(biāo)準(zhǔn):基本的正則表達(dá)式(BRE),擴(kuò)展的正則表達(dá)式(ERE)。ERE包括BRE功能和另外其它的概念。

許多程序中都使用了正則表達(dá)式,包括xsh,egrep,sed,vi以及在UNIX平臺(tái)下的程序。它們可以被很多語言采納,如HTML 和XML,這些采納通常只是整個(gè)標(biāo)準(zhǔn)的一個(gè)子集。

比你想象的還要普通
隨著正則表達(dá)式移植到交叉平臺(tái)的程序語言的發(fā)展,這的功能也日益完整,使用也逐漸廣泛。網(wǎng)絡(luò)上的搜索引擎使用它,e-mail程序也使用它,即使你不是一個(gè)UNIX程序員,你也可以使用規(guī)則語言來簡化你的程序而縮短你的開發(fā)時(shí)間。

正則表達(dá)式101
很多正則表達(dá)式的語法看起來很相似,這是因?yàn)槟阋郧澳銢]有研究過它們。通配符是RE的一個(gè)結(jié)構(gòu)類型,即重復(fù)操作。讓我們先看一看ERE標(biāo)準(zhǔn)的最通用的基本語法類型。為了能夠提供具有特定用途的范例,我將使用幾個(gè)不同的程序。

第二部分:
----------------------
字符匹配

正則表達(dá)式的關(guān)鍵之處在于確定你要搜索匹配的東西,如果沒有這一概念,Res將毫無用處。

每一個(gè)表達(dá)式都包含需要查找的指令,如表A所示。

Table A: Character-matching regular expressions
格式說明:
---------------
操作:
解釋:
例子:
結(jié)果:
----------------
.
Match any one character
grep .ord sample.txt
Will match “ford”, “lord”, “2ord”, etc. in the file sample.txt.
-----------------
[ ]
Match any one character listed between the brackets
grep [cng]ord sample.txt
Will match only “cord”, “nord”, and “gord”
---------------------
[^ ]
Match any one character not listed between the brackets

grep [^cn]ord sample.txt
Will match “lord”, “2ord”, etc. but not “cord” or “nord”

grep [a-zA-Z]ord sample.txt
Will match “aord”, “bord”, “Aord”, “Bord”, etc.

grep [^0-9]ord sample.txt
Will match “Aord”, “aord”, etc. but not “2ord”, etc.

重復(fù)操作符
重復(fù)操作符,或數(shù)量詞,都描述了查找一個(gè)特定字符的次數(shù)。它們常被用于字符匹配語法以查找多行的字符,可參見表B。

Table B: Regular expression repetition operators
格式說明:
---------------
操作:
解釋:
例子:
結(jié)果:
----------------

Match any character one time, if it exists
egrep “?erd” sample.txt
Will match “berd”, “herd”, etc. and “erd”
------------------
*
Match declared element multiple times, if it exists
egrep “n.*rd” sample.txt
Will match “nerd”, “nrd”, “neard”, etc.
-------------------
+
Match declared element one or more times
egrep “[n]+erd” sample.txt
Will match “nerd”, “nnerd”, etc., but not “erd”
--------------------
{n}
Match declared element exactly n times
egrep “[a-z]{2}erd” sample.txt
Will match “cherd”, “blerd”, etc. but not “nerd”, “erd”, “buzzerd”, etc.
------------------------
{n,}
Match declared element at least n times
egrep “.{2,}erd” sample.txt
Will match “cherd” and “buzzerd”, but not “nerd”
------------------------
{n,N}
Match declared element at least n times, but not more than N times
egrep “n[e]{1,2}rd” sample.txt
Will match “nerd” and “neerd”

第三部分:
----------------

錨是指它所要匹配的格式,如圖C所示。使用它能方便你查找通用字符的合并。例如,我用vi行編輯器命令:s來代表substitute,這一命令的基本語法是:

s/pattern_to_match/pattern_to_substitute/


Table C: Regular expression anchors
-------------
操作
解釋
例子
結(jié)果
---------------
^
Match at the beginning of a line
s/^/blah /
Inserts “blah “ at the beginning of the line
---------------
$
Match at the end of a line
s/$/ blah/
Inserts “ blah” at the end of the line
---------------
\<
Match at the beginning of a word
s/\
Inserts “blah” at the beginning of the word

egrep “\
Matches “blahfield”, etc.
------------------
\>
Match at the end of a word
s/\>/blah/
Inserts “blah” at the end of the word

egrep “\>blah” sample.txt
Matches “soupblah”, etc.
---------------
\b
Match at the beginning or end of a word
egrep “\bblah” sample.txt
Matches “blahcake” and “countblah”
-----------------
\B
Match in the middle of a word
egrep “\Bblah” sample.txt
Matches “sublahper”, etc.

間隔

Res中的另一可便之處是間隔(或插入)符號。實(shí)際上,這一符號相當(dāng)于一個(gè)OR語句并代表|符號。下面的語句返回文件sample.txt中的“nerd” 和 “merd”的句柄:

egrep “(n|m)erd” sample.txt

間隔功能非常強(qiáng)大,特別是當(dāng)你尋找文件不同拼寫的時(shí)候,但你可以在下面的例子得到相同的結(jié)果:

egrep “[nm]erd” sample.txt

當(dāng)你使用間隔功能與Res的高級特性連接在一起時(shí),它的真正用處更能體現(xiàn)出來。


第四部分:
----------------
一些保留字符
Res的最后一個(gè)最重要特性是保留字符(也稱特定字符)。例如,如果你想要查找“ne*rd”和“ni*rd”的字符,格式匹配語句“n[ei]*rd”與“neeeeerd” 和 “nieieierd”相符合,但并不是你要查找的字符。因?yàn)?#8216;*’(星號)是個(gè)保留字符,你必須用一個(gè)反斜線符號來替代它,即:“n[ei]\*rd”。其它的保留字符包括:

^ (carat)
. (period)
[ (left bracket}
$ (dollar sign)
( (left parenthesis)
) (right parenthesis)
| (pipe)
* (asterisk)
+ (plus symbol)
(question mark)
{ (left curly bracket, or left brace)
\ backslash
一旦你把以上這些字符包括在你的字符搜索中,毫無疑問Res變得非常的難讀。比如說以下的PHP中的eregi搜索引擎代碼就很難讀了。

eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$",$sendto)

你可以看到,程序的意圖很難把握。但如果你拋開保留字符,你常常會(huì)錯(cuò)誤地理解代碼的意思。

總結(jié)
在本文中,我們揭開了正則表達(dá)式的神秘面紗,并列出了ERE標(biāo)準(zhǔn)的通用語法。如果你想閱覽Open Group組織的規(guī)則的完整描述,你可以參見:Regular Expressions,歡迎你在其中的討論區(qū)發(fā)表你的問題或觀點(diǎn)。


另外一篇文章
----------------------------------------
正則表達(dá)式和Java編程語言
-----------------------------------------
類和方法

下面的類根據(jù)正則表達(dá)式指定的模式,與字符序列進(jìn)行匹配。

Pattern類

Pattern類的實(shí)例表示以字符串形式指定的正則表達(dá)式,其語 法類似于Perl所用的語法。

用字符串形式指定的正則表達(dá)式,必須先編譯成Pattern類的 實(shí)例。生成的模式用于創(chuàng)建Matcher對象,它根據(jù)正則表達(dá)式與任 意字符序列進(jìn)行匹配。多個(gè)匹配器可以共享一個(gè)模式,因?yàn)樗欠菍俚摹?br>
用compile方法把給定的正則表達(dá)式編譯成模式,然后用 matcher方法創(chuàng)建一個(gè)匹配器,這個(gè)匹配器將根據(jù)此模式對給定輸 入進(jìn)行匹配。pattern 方法可返回編譯這個(gè)模式所用的正則表達(dá) 式。

split方法是一種方便的方法,它在與此模式匹配的位置將給 定輸入序列切分開。下面的例子演示了:

/*
* 用split對以逗號和/或空格分隔的輸入字符串進(jìn)行切分。
*/
import java.util.regex.*;

public class Splitter {
public static void main(String[] args) throws Exception {
// Create a pattern to match breaks
Pattern p = Pattern.compile("[,\\s]+");
// Split input with the pattern
String[] result =
   p.split("one,two, three four , five");
for (int i=0; i
System.out.println(result[i]);
}
}

Matcher類

Matcher類的實(shí)例用于根據(jù)給定的字符串序列模式,對字符序 列進(jìn)行匹配。使用CharSequence接口把輸入提供給匹配器,以便 支持來自多種多樣輸入源的字符的匹配。

通過調(diào)用某個(gè)模式的matcher方法,從這個(gè)模式生成匹配器。 匹配器創(chuàng)建之后,就可以用它來執(zhí)行三類不同的匹配操作:

matches方法試圖根據(jù)此模式,對整個(gè)輸入序列進(jìn)行匹配。
lookingAt方法試圖根據(jù)此模式,從開始處對輸入序列進(jìn) 行匹配。
find方法將掃描輸入序列,尋找下一個(gè)與模式匹配的地方。

這些方法都會(huì)返回一個(gè)表示成功或失敗的布爾值。如果匹配成功,通過查詢 匹配器的狀態(tài),可以獲得更多的信息

這個(gè)類還定義了用新字符串替換匹配序列的方法,這些字符串的內(nèi)容如果需 要的話,可以從匹配結(jié)果推算得出。

appendReplacement方法先添加字符串中從當(dāng)前位置到下一個(gè) 匹配位置之間的所有字符,然后添加替換值。appendTail添加的 是字符串中從最后一次匹配的位置之后開始,直到結(jié)尾的部分。

例如,在字符串blahcatblahcatblah中,第一個(gè) appendReplacement添加blahdog。第二個(gè) appendReplacement添加blahdog,然后 appendTail添加blah,就生成了: blahdogblahdogblah。請參見示例 簡單的單詞替換。

CharSequence接口

CharSequence接口為許多不同類型的字符序列提供了統(tǒng)一的只 讀訪問。你提供要從不同來源搜索的數(shù)據(jù)。用String, StringBuffer 和CharBuffer實(shí)現(xiàn)CharSequence,,這樣就可以很 容易地從它們那里獲得要搜索的數(shù)據(jù)。如果這些可用數(shù)據(jù)源沒一個(gè)合適的,你可 以通過實(shí)現(xiàn)CharSequence接口,編寫你自己的輸入源。

Regex情景范例

以下代碼范例演示了java.util.regex軟件包在各種常見情形 下的用法:

簡單的單詞替換

/*
* This code writes "One dog, two dogs in the yard."
* to the standard-output stream:
*/
import java.util.regex.*;

public class Replacement {
public static void main(String[] args)
       throws Exception {
// Create a pattern to match cat
Pattern p = Pattern.compile("cat");
// Create a matcher with an input string
Matcher m = p.matcher("one cat," +
     " two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// Loop through and create a new String
// with the replacements
while(result) {
m.appendReplacement(sb, "dog");
result = m.find();
}
// Add the last segment of input to
// the new String
m.appendTail(sb);
System.out.println(sb.toString());
}
}

電子郵件確認(rèn)

以下代碼是這樣一個(gè)例子:你可以檢查一些字符是不是一個(gè)電子郵件地址。 它并不是一個(gè)完整的、適用于所有可能情形的電子郵件確認(rèn)程序,但是可以在 需要時(shí)加上它。

/*
* Checks for invalid characters
* in email addresses
*/
public class EmailValidation {
public static void main(String[] args)
           throws Exception {
          
String input = "@sun.com";
//Checks for email addresses starting with
//inappropriate symbols like dots or @ signs.
Pattern p = Pattern.compile("^\\.|^\\@");
Matcher m = p.matcher(input);
if (m.find())
System.err.println("Email addresses don‘t start" +
        " with dots or @ signs.");
//Checks for email addresses that start with
//www. and prints a message if it does.
p = Pattern.compile("^www\\.");
m = p.matcher(input);
if (m.find()) {
System.out.println("Email addresses don‘t start" +
  " with \"www.\", only web pages do.");
}
p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
m = p.matcher(input);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
boolean deletedIllegalChars = false;

while(result) {
deletedIllegalChars = true;
m.appendReplacement(sb, "");
result = m.find();
}

// Add the last segment of input to the new String
m.appendTail(sb);

input = sb.toString();

if (deletedIllegalChars) {
System.out.println("It contained incorrect characters" +
       " , such as spaces or commas.");
}
}
}

從文件中刪除控制字符

/* This class removes control characters from a named
* file.
*/
import java.util.regex.*;
import java.io.*;

public class Control {
public static void main(String[] args)
           throws Exception {
          
//Create a file object with the file name
//in the argument:
File fin = new File("fileName1");
File fout = new File("fileName2");
//Open and input and output stream
FileInputStream fis =
       new FileInputStream(fin);
FileOutputStream fos =
      new FileOutputStream(fout);

BufferedReader in = new BufferedReader(
     new InputStreamReader(fis));
BufferedWriter out = new BufferedWriter(
     new OutputStreamWriter(fos));

// The pattern matches control characters
Pattern p = Pattern.compile("{cntrl}");
Matcher m = p.matcher("");
String aLine = null;
while((aLine = in.readLine()) != null) {
m.reset(aLine);
//Replaces control characters with an empty
//string.
String result = m.replaceAll("");
out.write(result);
out.newLine();
}
in.close();
out.close();
}
}

文件查找

/*
* Prints out the comments found in a .java file.
*/
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;

public class CharBufferExample {
public static void main(String[] args) throws Exception {
// Create a pattern to match comments
Pattern p =
Pattern.compile("http://.*$", Pattern.MULTILINE);

// Get a Channel for the source file
File f = new File("Replacement.java");
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();

// Get a CharBuffer from the source file
ByteBuffer bb =
fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
Charset cs = Charset.forName("8859_1");
CharsetDecoder cd = cs.newDecoder();
CharBuffer cb = cd.decode(bb);

// Run some matches
Matcher m = p.matcher(cb);
while (m.find())
System.out.println("Found comment: "+m.group());
}
}

結(jié)論
現(xiàn)在Java編程語言中的模式匹配和許多其他編程語言一樣靈活了。可以在應(yīng) 用程序中使用正則表達(dá)式,確保數(shù)據(jù)在輸入數(shù)據(jù)庫或發(fā)送給應(yīng)用程序其他部分之 前,格式是正確的,正則表達(dá)式還可以用于各種各樣的管理性工作。簡而言之, 在Java編程中,可以在任何需要模式匹配的地方使用正則表達(dá)式。


JDK1.4之正規(guī)表示式
written by william chen(06/19/2002)

--------------------------------------------------------------------------------

什麼是正規(guī)表示式呢(Reqular Expressions)

就是針對檔案、字串,透過一種很特別的表示式來作search與replace

因?yàn)樵趗nix上有很多系統(tǒng)設(shè)定都是存放在文字檔中,因此網(wǎng)管或程式設(shè)計(jì)常常需要作搜尋與取代

所以發(fā)展出一種特殊的命令叫做正規(guī)表示式

我們可以很簡單的用 "s/<>

因此jdk1.4提供了一組正規(guī)表示式的package供大家使用

若是jdk1.4以下的可以到http://jakarta.apache.org/oro取得相關(guān)功能的package

剛剛列出的一串符號" s/

適用於j2sdk1.4的正規(guī)語法

"." 代表任何字元

正規(guī)式 原字串 符合之字串
. ab a
.. abc ab

"+" 代表一個(gè)或以個(gè)以上的字元
"*" 代表零個(gè)或是零個(gè)以上的字元

正規(guī)式 原字串 符合之字串
+ ab ab
* abc abc

"( )"群組

正規(guī)式 原字串 符合之字串
(ab)* aabab abab

字元類

正規(guī)式 原字串 符合之字串
[a-dA-D0-9]* abczA0 abcA0
[^a-d]* abe0 e0
[a-d]* abcdefgh abab


簡式

\d 等於 [0-9] 數(shù)字
\D 等於 [^0-9] 非數(shù)字
\s 等於 [ \t\n\x0B\f\r] 空白字元
\S 等於 [^ \t\n\x0B\f\r] 非空白字元
\w 等於 [a-zA-Z_0-9] 數(shù)字或是英文字
\W 等於 [^a-zA-Z_0-9] 非數(shù)字與英文字

每一行的開頭或結(jié)尾

^ 表示每行的開頭
$ 表示每行的結(jié)尾

--------------------------------------------------------------------------------

正規(guī)表示式 java.util.regex 相關(guān)的類別

 Pattern—正規(guī)表示式的類別
 Matcher—經(jīng)過正規(guī)化的結(jié)果
 PatternSyntaxExpression—Exception thrown while attempting to compile a regular expression

範(fàn)例1: 將字串中所有符合"<"的字元取代成"lt;"

import java.io.*;
import java.util.regex.*;
/**
* 將字串中所有符合"<"的字元取代成"lt;"
*/
public static void replace01(){
// BufferedReader lets us read line-by-line
Reader r = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( r );
Pattern pattern = Pattern.compile( "<" ); // 搜尋某字串所有符合‘<‘的字元
try{
while (true) {
String line = br.readLine();
// Null line means input is exhausted
if (line==null)
break;
Matcher a = pattern.matcher(line);
while(a.find()){
System.out.println("搜尋到的字元是" + a.group());
}
System.out.println(a.replaceAll("lt;"));// 將所有符合字元取代成lt;
}
}catch(Exception ex){ex.printStackTrace();};
}

範(fàn)例2:

import java.io.*;
import java.util.regex.*;
/**
* 類似StringTokenizer的功能
* 將字串以","分隔然後比對哪個(gè)token最長
*/
public static void search01(){
// BufferedReader lets us read line-by-line
Reader r = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( r );
Pattern pattern = Pattern.compile( ",\\s*" );// 搜尋某字串所有","的字元
try{
while (true) {
String line = br.readLine();
String words[] = pattern.split(line);
// Null line means input is exhausted
if (line==null)
break;
// -1 means we haven‘t found a word yet
int longest=-1;
int longestLength=0;
for (int i=0; i
System.out.println("分段:" + words[i] );
if (words[i].length() > longestLength) {
longest = i;
longestLength = words[i].length();
}
}
System.out.println( "長度最長為:" + words[longest] );
}
}catch(Exception ex){ex.printStackTrace();};
}

--------------------------------------------------------------------------------

其他的正規(guī)語法

/^\s* # 忽略每行開始的空白字元
(M(s|r|rs)\.) # 符合 Ms., Mrs., and Mr. (titles)

本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊舉報(bào)
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Linux下的Grep命令使用方法詳細(xì)介紹
Java正則表達(dá)式的總結(jié)
JAVA正則表達(dá)式實(shí)例教程AAA
Java 正則表達(dá)式詳解 – 碼農(nóng)網(wǎng)
Android基礎(chǔ)之最新正則表達(dá)式
爬蟲大佬,把他總結(jié)的正則表達(dá)式使用給我了!
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服