欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
CSDN技術(shù)中心 正則表達式
 

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

支持多種平臺


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

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

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

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

正則表達式101
很多正則表達式的語(yǔ)法看起來(lái)很相似,這是因為你以前你沒(méi)有研究過(guò)它們。通配符是RE的一個(gè)結構類(lèi)型,即重復操作。讓我們先看一看ERE標準的最通用的基本語(yǔ)法類(lèi)型。為了能夠提供具有特定用途的范例,我將使用幾個(gè)不同的程序。

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

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

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

Table A: Character-matching regular expressions
格式說(shuō)明:
---------------
操作:
解釋?zhuān)?br>例子:
結果:
----------------
.
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.

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

Table B: Regular expression repetition operators
格式說(shuō)明:
---------------
操作:
解釋?zhuān)?br>例子:
結果:
----------------

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來(lái)代表substitute,這一命令的基本語(yǔ)法是:

s/pattern_to_match/pattern_to_substitute/


Table C: Regular expression anchors
-------------
操作
解釋
例子
結果
---------------
^
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í)際上,這一符號相當于一個(gè)OR語(yǔ)句并代表|符號。下面的語(yǔ)句返回文件sample.txt中的“nerd” 和 “merd”的句柄:

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

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

egrep “[nm]erd” sample.txt

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


第四部分:
----------------
一些保留字符
Res的最后一個(gè)最重要特性是保留字符(也稱(chēng)特定字符)。例如,如果你想要查找“ne*rd”和“ni*rd”的字符,格式匹配語(yǔ)句“n[ei]*rd”與“neeeeerd” 和 “nieieierd”相符合,但并不是你要查找的字符。因為‘*’(星號)是個(gè)保留字符,你必須用一個(gè)反斜線(xiàn)符號來(lái)替代它,即:“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
一旦你把以上這些字符包括在你的字符搜索中,毫無(wú)疑問(wèn)Res變得非常的難讀。比如說(shuō)以下的PHP中的eregi搜索引擎代碼就很難讀了。

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

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

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


另外一篇文章
----------------------------------------
正則表達式和Java編程語(yǔ)言
-----------------------------------------
類(lèi)和方法

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

Pattern類(lèi)

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

用字符串形式指定的正則表達式,必須先編譯成Pattern類(lèi)的 實(shí)例。生成的模式用于創(chuàng )建Matcher對象,它根據正則表達式與任 意字符序列進(jìn)行匹配。多個(gè)匹配器可以共享一個(gè)模式,因為它是非專(zhuān)屬的。

用compile方法把給定的正則表達式編譯成模式,然后用 matcher方法創(chuàng )建一個(gè)匹配器,這個(gè)匹配器將根據此模式對給定輸 入進(jìn)行匹配。pattern 方法可返回編譯這個(gè)模式所用的正則表達 式。

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

/*
* 用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類(lèi)

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

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

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

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

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

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

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

CharSequence接口

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

Regex情景范例

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

簡(jiǎn)單的單詞替換

/*
* 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());
}
}

電子郵件確認

以下代碼是這樣一個(gè)例子:你可以檢查一些字符是不是一個(gè)電子郵件地址。 它并不是一個(gè)完整的、適用于所有可能情形的電子郵件確認程序,但是可以在 需要時(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());
}
}

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


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

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

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

就是針對檔案、字串,透過(guò)一種很特別的表示式來(lái)作search與replace

因為在unix上有很多系統設定都是存放在文字檔中,因此網(wǎng)管或程式設計常常需要作搜尋與取代

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

我們可以很簡(jiǎn)單的用 "s/<>

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

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

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

適用於j2sdk1.4的正規語(yǔ)法

"." 代表任何字元

正規式 原字串 符合之字串
. ab a
.. abc ab

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

正規式 原字串 符合之字串
+ ab ab
* abc abc

"( )"群組

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

字元類(lèi)

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


簡(jiǎn)式

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

每一行的開(kāi)頭或結尾

^ 表示每行的開(kāi)頭
$ 表示每行的結尾

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

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

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

範例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();};
}

範例2:

import java.io.*;
import java.util.regex.*;
/**
* 類(lèi)似StringTokenizer的功能
* 將字串以","分隔然後比對哪個(gè)token最長(cháng)
*/
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( "長(cháng)度最長(cháng)為:" + words[longest] );
}
}catch(Exception ex){ex.printStackTrace();};
}

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

其他的正規語(yǔ)法

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

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

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久