Regular Expression Syntax Reference
文章推薦指數: 80 %
Example1: When pattern "\d\d" matches "abc123", match result: success; substring matched: "12"; position: starts at 3, ends at 5. ... Example2: When pattern "a.\d ...
Home
Start
Engine
Tools
Applications
Content:
·Introduction
------------
·Common
·Escapedcharacter
·Charactersets
·Customsets
·Quantifier
·Specialpuncts
------------
·Greedyorreluctant
·Backward
·Assertion
------------
·Othercommon
·Moreprompts
RegexTool:
RegexMatchTracer
2.1-Free
RegexMatchTracer3.0-Newrelease
(Thenewreleasewilltellyouwhereinyour
regexfailedtomatch!)
RegularExpressionSyntax
[Allrightsreserved:http://www.regexlab.com/en/regref.htm]
Introduction
Regularexpressionistoexpressacharacteristicinastring,andthentomatchanotherstringwiththecharacteristic.Forexample,pattern"ab+"means"one'a'andatleastone'b'",so"ab","abb","abbbbbbb"matchthepattern.
Regularexpressionisusedto:(1)testastringwhetheritmatchesapattern,suchasaemailaddress.(2)tofindasubstringwhichmatchescertainpattern,fromawholetext.(3)todocomplexreplacementinatext.
Itisverysimpletostudyregularexpressionsyntax,andthefewabstractconceptscanbeunderstoodeasilytoo.Manyarticlesdoesnotintroduceitsconceptsfromsimpleonestoabstractonesstepbystep,sosomepersonsmayfeelitisdifficult
tostudy.Ontheotherhand,eachregularexpressionengine'sdocumentwilldescribeitsspecialfunction,butthispartofspecialfunctionisnotwhatweshouldstudyfirst.
Everyexampleinthisarticlehasalinktotestpage.Nowlet'sbegin!
1.RegularExpressionBasicSyntax
1.1CommonCharacters
Letters,numbers,theunderline,andpunctuationswithnospecialdefinitionare"commoncharacters".Whenregularexpressionmatchesastring,acommoncharactercanmatchthesamecharacter.
Example1:Whenpattern"c"matchesstring"abcde",matchresult:success;substringmatched:"c";position:startsat2,endsat3.
Example2:Whenpattern"bcd"matchesstring"abcde",matchresult:success;substringmatched:"bcd";position:startsat1,endsat4.
1.2Simpleescapedcharacters
Nonprintingcharacterswhichweknow:
Expression
Matches
\r,\n
Carriagereturn,newlinecharacter
\t
Tabs
\\
Matches"\"itself
Somepunctuationsarespeciallydefinedinregularexpression.Tomatchthesecharactersinstring,add"\"inpattern.Forexample:^,$hasspecialdefinition,soweneedtouse"\^"and"\$"tomatchthem.
Expression
Matches
\^
Matches"^"itself
\$
Matches"$"itself
\.
Matchesdot(.)itself
Theseescapedcharactershavethesameeffectas"commoncharacters":tomatchacertaincharacter.
Example1:Whenpattern"\$d"matchesstring"abc$de",matchresult:success;substringmatched:"$d";position:startsat3,endsat5.
1.3Expressionmatchesanyoneofmanycharacters
Someexpressionscanmatchanyoneofmanycharacters.Forexample:"\d"canmatchanynumbercharacter.Eachoftheseexpressionscanmatchonlyonecharacteratonetime,thoughtheycanmatchanycharacterofacertaingroupofcharacters.
Expression
Matches
\d
Anydigitcharacter,anyoneof0~9
\w
Anyalpha,numeric,underline,anyoneofA~Z,a~z,0~9,_
\s
Anyoneofspace,tab,newline,return,ornewpagecharacter
.
'.'matchesanycharacterexceptthenewlinecharacter(\n)
Example1:Whenpattern"\d\d"matches"abc123",matchresult:success;substringmatched:"12";position:startsat3,endsat5.
Example2:Whenpattern"a.\d"matches"aaa100",matchresult:success;substringmatched:"aa1";position:startsat1,endsat4.
1.4Customexpressionmatchesanyoneofmanycharacters
Expressionusessquarebrackets[]tocontainaseriesofcharacters,itcanmatchanyoneofthem.Uses[^]tocontainaseriesofcharacters,itcanmatchanyonecharacterexceptcharacterscontained.
Expression
Matches
[ab5@]
Matches"a"or"b"or"5"or"@"
[^abc]
Matchesanycharacterexcept"a","b","c"
[f-k]
Anycharacteramong"f"~"k"
[^A-F0-3]
Anycharacterexcept"A"~"F","0"~"3"
Example1:Whenpattern"[bcd][bcd]"matches"abc123"
,matchresult:success;substringmatched:"bc";position:startsat1,endsat3.
Example2:Whenpattern"[^abc]"matches"abc123",matchresult:success;substringmatched:"1";position:startsat3,endsat4.
1.5Specialexpressiontoquantifymatching
Allexpressionsintroducedbeforecanmatchcharacteronlyonetime.Ifaexpressionisfollowedbyaquantifier,itcanmatchesmorethanonetimes.
Forexample:wecanusethepattern"[bcd]{2}"insteadof"[bcd][bcd]".
Expression
Function
{n}
Matchexactlyntimes,example:"\w{2}"equals"\w\w";"a{5}"equals "aaaaa"
{m,n}
Atleastmbutnomorethanntimes:
"ba{1,3}"matches"ba","baa","baaa"
{m,}
Matchatleastntimes:
"\w\d{2,}"matches"a12","_456","M12344"...
?
Match1or0times,equivalentto{0,1}:
"a[cd]?"matches"a","ac","ad".
+
Match1ormoretimes,equivalentto{1,}:
"a+b"matches"ab","aab","aaab"...
*
Match0ormoretimes,equivalentto{0,}:
"\^*b"matches"b","^^^b"...
Example1:Whenpattern"\d+\.?\d*"matches"Itcosts$12.5",matchresult:success;substringmatched:"12.5";position:startsat10,endsat14.
Example2:Whenpattern"go{2,8}gle"matches"Adsbygoooooogle",matchresult:success;substringmatched:"goooooogle";position:startsat7,endsat17.
1.6Somespecialpunctuationswithabstractfunction
Somepunctuationsinpatternhavespecialfunction:
Expression
Function
^
Matchthebeginningofthestring
$
Matchtheendofthestring
\b
Matchawordboundary
Moreexamplestohelpyoutounderstand.
Example1:Whenpattern"^aaa"matches"xxxaaaxxx",matchresult:failed.Because"^"mustmatchthebeginningofthestring.Itcouldmatchsuccessfullyonconditionthat"aaa"isatthe
beginningofthestring,suchas"aaaxxxxxx".
Example2:Whenpattern"aaa$"matches"xxxaaaxxx",matchresult:failed.Bacause"$"mustmatchtheendofthestring.Itcouldmatchsuccessfullyonconditionthat"aaa"isattheendofthe
string,suchas"xxxxxxaaa".
Example3:Whenpattern".\b."matches"@@@abc",matchresult:success;substringmatched:"@a";position:startsat2,endsat4.
Furtherexplanation:"\b"issimilarto"^"and"$",matchesnocharacteritself,butitrequirea'\w'characteratitsoneside,anothernot'\w'characterattheotherside.
Example4:Whenpattern"\bend\b"matches"weekend,endfor,end",matchresult:success;substringmatched:"end";position:startsat15,endsat18.
Somespecialpunctuationcanmakeeffectonothersub-patterns:
Expression
Function
|
Alternation,matcheseitherleftsideorrightside
()
(1).Letsub-patternsinittobeawholepartwhenitisquantified.
(2).Matchresultofsub-patternsinitcanberetrievedindividually
Example5:Whenpattern"Tom|Jack"matchesstring"I'mTom,heisJack",matchresult:success;substringmatched:"Tom";position:startsat4,endsat7.Whenmatchnext,
matchresult:success;substringmatched:"Jack";position:startsat15,endsat19.
Example6:Whenpattern"(go\s*)+"matches"Let'sgogogo!",matchresult:success;substringmatched:"gogogo";position:startsat6,endsat14.
Example7:Whenpattern"¥(\d+\.?\d*)"matches"$10.9,¥20.5",matchresult:success;substringmatched:"¥20.5";position:startsat6,endsat10.Match
resultofsub-patternsin"()"is:"20.5".
2.Regularexpressionadvancedsyntax
2.1Reluctantorgreedyquantifiers
Thereareservalmethodtoquantifysubpattern,suchas:"{m,n}","{m,}","?","*","+".Bydefault,aquantifiedsubpatternis"greedy",thatis,itwillmatchasmanytimesaspossible(givenaparticularstartinglocation)whilestillallowing
therestofthepatterntomatch.Forexample,tomatch"dxxxdxxxd":
Expression
Matchresult
(d)(\w+)
"\w+"matchesallcharacters"xxxdxxxd"behindof"d"
(d)(\w+)(d)
"\w+"matchesallcharacters"xxxdxxx"betweenthefirst"d"andthelast"d".Inordertoletthewholepatternmatchsuccess,"\w"hastogiveupthelast"d",althoughitcanmatchthelast"d"too.
Thusitcanbeseenthat:when"\w+"matches,itwillmatchasmanycharactersaspossible.Inthesecondexample,itdoesnotmatchthelast"d",butthisisinordertoletthewholepatternmatchsuccessfully.Patternwith"*"or"{m,n}"will
alsomatchasmanytimesaspossible,patternwith"?"willmatchifpossible.Thistypeofmatchingiscalled"greedymatching".。
ReluctantMatching:
Tofollowthequantifierwitha"?",itcanletthepatterntomatchtheminimumnumberoftimespossible.Thistypeofmatchingiscalledreluctantmatching.Inordertoletthewholepatternmatchsuccessfully,thereluctantpatternmaymatcha
fewmoretimesifitisrequired.Forexample,tomatch"dxxxdxxxd":
Expression
Matchresult
(d)(\w+?)
"\w+?"matchasfewtimesaspossible,so"\w+?"matchesonlyone"x"
(d)(\w+?)(d)
Inordertoletthewholepatternmatchsuccessfully,"\w+?"hastomatch"xxx".So,matchresultis:"\w+?"matches"xxx"
Moreexamples:
Example1:Whenpattern"
aa
bb
aa
bb
aa
bb
延伸文章資訊
- 1Regex.Match Method (System.Text.RegularExpressions)
Searches an input string for a substring that matches a regular expression pattern and returns th...
- 2How can I extract a portion of a string variable using regular ...
We will show some examples of how to use regular expression to extract and/or ... Where n is the ...
- 3Extract a substring from a string in Python (position, regex)
You can extract a substring by specifying the position and number of characters, or with regular ...
- 4Python Extract Substring Using Regex - Linux Hint
In a programming language, a Regular Expression written as (RE or regex) is a text string that is...
- 5How to extract a substring using regex - java - Stack Overflow
While substring looks for a specific string or value, regex looks for a format. It's more and mor...