Вы находитесь на странице: 1из 4

8.6.

2015

JavaScriptRegularExpressionsSimpleUsage

Home

ComputerMain

Products

Tutorials

CompletelyFree

MailingList

Ken Ward's Java Script Tutorial ...

RegularExpressionSimpleUsage
Regularexpressionsaren'treallythatdifficult,eventhoughtheywouldn'twinanybeautycontests.Weallknow
someofthem,suchasthe"*"andthe"?"whichareusedinwindow'ssearches.
ThispagewaswrittenoriginallyforthephptutorialandhasbeenmodifiedforJavaScript.
WhenusingtheseinJavaScript,theregularexpressionisenclosedinforwardslashes,andthewholeisenclosed
inquotes.
UsethispagetotryoutregularexpressionsinJavaScript.Itisprobablybettertoexperimentwithyourown
regularexpressionsthanonlytoreadaboutthem.TryouttheexamplesonthispageintheRegularExpression
Checker.
Onthispage:
1. Usage
a.
i. match
ii. replace
iii. search
b. Flags(i,g,m)
c. Period,Asterisk,PlusandQuestionMark
i. ThePeriod
ii. TheAsterisk(*)
iii. ThePlus(+)
iv. TheQuestionMark(?)
d. TheBeginning(^)andtheEnd($),andtheCharacterClass([])
i. CharacterClass([])
ii. Selectingstringsbeginningwith...
iii. Selectingstringsendingwith...
iv. Selectingstringsbeginningwith...andendingwith...
i. SpecialcharactersbecomenormalcharactersinaCharacterClass
e. Matchingagivennumberoftimes{2}
f. Sayingwhatyoudon'twant[^...
g. ThePipes,orgivingachoiceofmatch
h. EmailChecker

Usage
Notearegularexpression,suchas/o/isNOTastring(soitisneverenclosedinquotes).Whenaregular
expressionisenteredbyauserinaform,weneedtochangetheformvaluefromastring.Forexample

str="hellofolks"
re="/o/"//thisisastring,soitwon'twork
re=eval(re)//changeittoanobject
check=str.replace(re,"a")
alert(check)

match
str="hellofolks"
re=/o/
check=str.match(re)
alert(check)
//resultis"o"
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm

1/4

8.6.2015

JavaScriptRegularExpressionsSimpleUsage

//otherwiseitreturnsnull

replace
str="hellofolks"
re=/o/
check=str.replace(re,"a")
alert(check)
//resultis"hellafolks"

search
searchcanbeusedtofindthepositionofthefirstoccurrenceofamatch:

str="hellofolks"
re="/o/"
re=eval(re)
check=str.search(re)
document.write(check)
//resultis4

Flags (i, g, m)
Theiflagmakesthesearchcaseinsensitive.Thegmakesthesearchglobal,findingallmatchesandnotjustthe
first.Andthemflagcoversmultiplelines.
/rea/matchesbread
/rea/imatchesbReAd
/rea/gmatchesbreadbREAdbread
/rea/gimatchesbreadbREAdbread

Period, Asterisk, Plus and Question Mark


The Period
Theperiod(.)matchesanycharacter.
So"breadreadtedbaa".match(/.b./)matches"b"(ofba).Thatis,thespaceandthe"b".Itdoesn't

matchthe"b"inbread,becausethereisnocharacterbeforethe"b"inbread.Theremustbeoneor
morecharactersinthe"."space.

The Asterisk (*)


Theasterisk(*)matchesoneormoreornoneofthepreceding.

"breadreadtedbaa".match(/b*d/)matches"e"inbread.Itdoesn'tcareaboutthe"b"becauseitmatcheszero
ormoreofthepreceding.
/cat*/gmatchesallthecatsin"catcatamarancaterconcatenate".
Oftenwemustescapetheasteriskinjavascriptbecause/*lookslikeacommenttojavascript.Weneed,therefore
towrite/\\*/
Thequestionmarkwilloftenbeescapedtoo.

The Plus (+)


Theplus(+)matchesoneormoreoftheprecedingcharacter.Itisliketheasterisk(*),butmusthaveatleastone
characterpresent.Theasteriskgivesustheseresults:
str='caatctccatcatatat'
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm

2/4

8.6.2015

JavaScriptRegularExpressionsSimpleUsage

re=/c(at)*/g
reis:/c(at)*/g
str.match(/c(at)*/g)gives:"c,c,c,cat,catatat"
However,theplusgivesus:
str='caatctccatcatatat'
re=/c(at)+/g
reis:/c(at)+/g
str.match(/c(at)+/g)gives:"cat,catatat"
str.search(/c(at)+/g)givestheindexofthefirstoccurence:11
Thatis,theremustbeatleastoneprecedingitemtogiveamatch.Notethebrackets(at)beforetheplusmeans
thatthewholeofthecontentsofthebracketareconsidered.Inthiscase,theymustoccuratleastoncefora
match.

The Question Mark (?)


Thequestionmark(?)isliketheperiod,butunliketheperiod,itcantake0ofthepreviousitems.
Insummary,then,theasterisk(*)matches0ormoreoftheprecedingitems,andtheplus(+)matches1ormore
oftheprecedingitems.
Thequestionmarkmatches0ormoreoftheprecedingcharacters,whilsttheperiod(.)matches1ormore.
Forinstance
Thequestionmarkfinds5c's(Notewehavetoescapethe?withtwobackslashes!):
str='caatctccatcatatat'
re=/\\?c/g
reis:/\\?c/g
str.match(/\\?c/g)gives:"c,c,c,c,c"
str.search(/\\?c/g)givestheindexofthefirstoccurence:0
Whilstthedotgivesus(only4c's):
str='caatctccatcatatat'
re=/.c/g
reis:/.c/g
str.match(/.c/g)gives:"c,c,c,c"
str.search(/.c/g)givestheindexofthefirstoccurence:5
Thequestionmarktakeszeroormoreoftheprecedingforamatch,butthedotmusthaveatleastoneitem.

The Beginning (^) and the End ($), and the Character Class
([])
Character Class ([])
Well,let'sstartattheendwiththeCharacterClass.Forinstance,/[09]/selectsallthenumbercharacters,and
/[aeiou]/selectsallthelowercasevowels./[az]/selectsallthelowercaseletters,and/[AZ]/selectsallthe
uppercaseletters.

Selecting strings beginning with ...


Thecaret(^)isusedtomatchstringsbeginningwithcertaincharacters.So/^[AZ]/matchesanycapitalletter
beginningaword.SothiswillmatchtheBinBand0.Ifweaddadot(.)likethis,/^[AZ]./,itwillmatchany
stringbeginningwithacapitalletterhavinganycharacterafterit.SothismatchesBainBand0.
/^[AZ].+/willmatchthewholewordBand0.

Selecting strings ending with...


Thedollarsign($)isusedtoselectmatchesattheendofastring.Isupposethedollarsignisusedherebecause
intheendyouhavetopay(!!!).
/[AZ]$/willmatchastringendinginacapitalletter.SoitmatchestheDinBanD,butdoesnotmatchinBand.
Thenextexampleisoneofbeginningandendingwithaparticularpattern.
str='Billhasacoat'
re=/^[AZ].+(at)$/g
reis:/^[AZ].+(at)$/g
str.match(/^[AZ].+(at)$/g)gives:"Billhasacoat"
str.search(/^[AZ].+(at)$/g)givestheindexofthefirstoccurence:0
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm

3/4

8.6.2015

JavaScriptRegularExpressionsSimpleUsage

Selecting strings beginning with ... and ending with ...


/^[09].+[.]$/willmatchthestring1band.,butnotband.
Special characters become normal characters in a Character Class
Thefullstop,oranyspecialcharacterinaCharacterClass,isnolongeraspecialcharacter.Sointheexample,
thedotin[.]matchesadotonly,whereas,thedotin".+"matchesanycharacter(andisaspecialcharacterhere.
Tocontinuewithbeginningandending...
/^[AZ].+[.]$/willmatchastringbeginningwithacapitalletterandendingwithafullstop(.).Soitwillmatch
"Band.",butnot"Band",or"band.".

Matching a given number of times {2}


/(\.).{3}/willmatchastringcontainingaperiod(.)followedbythreecharacters.Soitwillmatch".com"in
".com",or".comm",butnot".co".Itwillalsoaccept".007".(Notethedot(.)hasbeenescapedtomakeitareal
dotandnotaspecialcharacter(\.))
/(\.)[azAZ]{3}$/willacceptonlystringsendingwithadotand3letters,eitherloweroruppercase.
/(\.)[azAZ]{2,5}$/willacceptanendingconsistingoflettersbeginningwithafullstop(.)andhavingbetween
2and5letters.Soitwillaccept"my.co","my.commm",butnot"my.commmm".

Saying what you don't want [^...


Thecaret(^)servestosaywhatthebeginningshouldbe,butinsideacharacterclass,itmeansthatnoneofthe
charactersintheclassareallowedinamatch.
/^[^aeiou]./willselectstringsbeginningwithanythingexceptalowercasevowel.
Intheaboveexample,thefirstcaretsaysthatthisisamatchforthebeginning,andtheoneinsidethecharacter
classsaysthecontentsareexcluded.

The Pipes, or giving a choice of match


Youcanusealternativesinregularexpressions.Thesigntouseiscalledapipe(|).Thefollowingexpression:
/^[az]|[09]/matchesstringsbeginningwithlowercaselettersorwithnumbers.Thepipe(|)indicatesachoice.
/(A|b)$/matchesanystringendingwithacapitalAoralowercaseb.Thepipe(|)indicatesachoice.

Email Checker
Thefollowingisanexampleofanemailchecker.Therearemanysuchregularexpressions,andnoneofthem
workwithallemailaddresses.
/^[azAZ09][azAZ09_\s]+@[azAZ09\s].+\.[azAZ]{2,5}$/

http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm

4/4

Вам также может понравиться