æ£è¦è¡¨é弿¯è¢«ç¨ä¾å¹é
å串ä¸åå
çµåçæ¨¡å¼ãå¨ JavaScript ä¸ï¼æ£è¦è¡¨éå¼ä¹æ¯ç©ä»¶ï¼éäºæ¨¡å¼å¨ RegExp
ç exec
å test
æ¹æ³ä¸ï¼ä»¥å String
ç match
ãreplace
ãsearch
ãsplit
çæ¹æ³ä¸è¢«éç¨ãéä¸ç« ç¯å°è§£èªª JavaScript ä¸çæ£è¦è¡¨éå¼ã
ä½ å¯ééä¸åå ©ç¨®æ¹æ³å»åµå»ºä¸æ¢æ£è¦è¡¨éå¼ï¼
ä½¿ç¨æ£è¦è¡¨éå¼åé¢å¼ï¼regular expression literalï¼ï¼å
å«å
©å /
åå
ä¹éçæ¨¡å¼å¦ä¸ï¼
æ£è¦è¡¨éå¼åé¢å¼å¨ script è¼å ¥ææè¢«ç·¨è¯ï¼ç¶æ£è¦è¡¨éå¼çºå®å¼æï¼ä½¿ç¨æ¤æ¹æ³å¯ç²å¾è¼ä½³æè½ã
æå¼å« RegExp
ç©ä»¶ç建æ§å½å¼ï¼å¦ä¸ï¼
var re = new RegExp("ab+c");
使ç¨å»ºæ§å彿¸ä¾å³æç·¨è¯æ£å表éå¼ï¼ç¶æ¨¡å¼æç°åãäºå æªç¥å¹é 模å¼ãæè ä½ å°å¾å ¶ä»å°æ¹å徿ï¼ä½¿ç¨å»ºæ§å彿¸å°è¼çºåé©ã
æ°å¯«æ£è¦è¡¨éæ¨¡å¼æ£è¦è¡¨é模å¼ç±æ¸åç°¡æåå
çµæï¼ä¾å¦ /abc/
ï¼ææ¯ç±ç°¡æåå
åç¹æ®ç¬¦èçµåèæï¼ä¾å¦ /ab*c/
ã/Chapter (\d+)\.\d*/ )
ãæå¾ä¸åç¯ä¾ç¨å°äºæ¬èï¼é卿£è¦è¡¨éå¼ä¸ç¨ä½è¨æ¶çµï¼ä½¿ç¨æ¬èçå¹é
å°æè¢«çå°å¾é¢ä½¿ç¨ï¼å¨ä½¿ç¨å¸¶æ¬èçé
å°ååä¸²ææ´å¤è§£éã
ç°¡æçæ¨¡å¼æ¯æä½ æ¾å°çç´æ¥å¹é
ææ§æçãæ¯å¦ï¼/abc/
é忍¡å¼å°±å¹é
äºå¨ä¸åå符串ä¸ï¼å
å
å符 'abc'
åæåºç¾ä¸¦æç
§éåé åºãéå
©åå¥åä¸ãHi, do you know your abc's?ãåãThe latest airplane designs evolved from slabcraft.ãå°±æå¹é
æåãå¨ä¸é¢çå
©å實ä¾ä¸ï¼å¹é
çæ¯åå符串 'abc'ãå¨å符串ä¸ç "Grab crab"('ab c') ä¸å°ä¸æè¢«å¹é
ï¼å çºå®ä¸å
å«ä»»ä½ç 'abc' å符串ã
ç¶ä½ éè¦æå°ä¸åæ¯ç´æ¥å¹é
éè¦æ´å¤æ¢ä»¶çå¹é
ï¼æ¯å¦æå°ä¸æå¤å 'b'ï¼æè
æå°ç©ºæ ¼ï¼é£éº¼é忍¡å¼å°è¦å
å«ç¹æ®å符ãä¾å¦ï¼ æ¨¡å¼ /ab*c/
å¹é
äºä¸åå®ç¨ç 'a' å¾é¢è·äºé¶æå¤å 'b'ï¼* çæææ¯åé¢ä¸é
åºç¾äºé¶æå¤åï¼ï¼ä¸å¾é¢è·è 'c' çä»»ä½å符çµåãå¨å符串 "cbbabbbbcdebc" ä¸ï¼é忍¡å¼å¹é
äºåå符串 "abbbbc"ã
ä¸é¢çè¡¨æ ¼ååºäºå¨æ£å表éå¼ä¸å¯ä»¥å©ç¨çç¹æ®åç¬¦å®æ´å表以åæè¿°ã
åå 解說\
åæç·æ¾å¨éç¹æ®ç¬¦èåé¢ï¼ä½¿éç¹æ®ç¬¦èä¸æè¢«éåè¯åºï¼ä»£è¡¨ç¹æ®ä½ç¨ã ä¾å¦ï¼'b' å¦ææ²æ '\' å¨åé ï¼åè½æ¯æ¾åºå°å¯« bï¼è¥æ¹çº '\b' åä»£è¡¨çæ¯éçåè½ï¼block ç¨æã /\bter\b/.test("interest") //false /\bter\b/.test("in ter est") //true /a*/
æ¾åº 0 åææ¯ 1 å以ä¸ç aï¼è /a\*/ æ¾åº 'a*' éåå串 /aaaa*/g.test("caaady") //true /a\*/.test("caaady") //false '\' ä¹è½ä½¿èªèº«è¡¨ç¾åºä¾ï¼è¡¨ç¾ '\' ï¼å¿
é 以 '\\' 表éã /[\\]/.test(">\\<") //true ^
å¹é
輸å
¥çéé ï¼å¦æ multiline flag 被è¨çº trueï¼åæå¹é
æè¡åå
å¾ãä¾å¦ï¼/^A/
䏿å¹é
ãan Aãç Aï¼ä½æå¹é
ãAn Eãä¸ç Aãã^
ãåºç¾å¨åå
鿍¡å¼çåé¦ä¸æä¸åçææï¼è©³è¦è£åå
éã $
å¹é
輸å
¥ççµå°¾ï¼å¦æ multiline flag 被è¨çº trueï¼åæå¹é
æè¡åå
ãä¾å¦ï¼/t$/
䏿å¹é
ãeaterãä¸ç tï¼å»æå¹é
ãeatãä¸ç tã *
å¹é
åä¸åå
0 è³å¤æ¬¡ã ä¸é¢èä¾è¦æ±åºæ¬ 'aaaa' ï¼'a*' å¾é¢æ 0 åæå¤å a çææ /aaaaa*/g.test("caaady") //false ä¾å¦ï¼/bo*/
å¹é
ãA ghost booooedãä¸ç booooããA bird warbledãä¸ç bï¼ä½å¨ãA goat gruntedãä¸ä¸æå¹é
ä»»ä½å串ã +
å¹é
åä¸åå
1 è³å¤æ¬¡ï¼çåæ¼ {1,}
ãä¾å¦ï¼/a+/
å¹é
ãcandyãä¸ç aï¼ä»¥åææãcaaaaaaandyãä¸ç aã ?
å¹é
åä¸åå
0 è³ 1 次ï¼çåæ¼ {0,1}
ãä¾å¦ï¼/e?le?/
å¹é
ãangelãä¸ç elããangleãä¸ç leã以åãosloãä¸ç lã妿æ¯ä½¿ç¨å¨ *
ã+
ã?
æ {}
ç quantifier ä¹å¾ï¼å°æä½¿éäº quantifier non-greedyï¼ä¹å°±æ¯åå¯è½å¹é
æå°çåå
ï¼ï¼èæ¤ç¸å°çæ¯ greedyï¼å¹é
åå¯è½å¤çåå
ï¼ãä¾å¦ï¼å¨ã123abcãä¸æç¨ /\d+/
å¯å¹é
ã123ãï¼ä½ä½¿ç¨ /\d+?/
å¨ç¸åå串ä¸åªè½å¹é
ã1ãã Also used in lookahead assertions, as described in the x(?=y)
and x(?!y)
entries of this table. .
ï¼å°æ¸é»ï¼å¹é
é¤äºæè¡ç¬¦èä¹å¤çå®ä¸åå
ãä¾å¦ï¼/.n/ å¹é
ãnay, an apple is on the treeãä¸ç an å onï¼ä½å¨ãnayã䏿²æå¹é
ã (x)
Capturing Parentheses å¹é
'x' 並è¨ä½æ¤æ¬¡çå¹é
ï¼å¦ä¸é¢çç¯ä¾æç¤ºãå¨ æ£å表é示 /(foo) (bar) \1 \2/ ä¸ç (foo) è (bar) å¯å¹é
äº "foo bar foo bar" éæ®µæåä¸çåå
©ååï¼è \1 è \2 åå¹é
äºå¾é¢çå
©ååãæ³¨æï¼ \1, \2, ..., \n 代表çå°±æ¯åé¢ç patternï¼ä»¥æ¬ç¯ä¾ä¾èªªï¼/(foo) (bar) \1 \2/ çåæ¼ /(foo) (bar) (foo) (bar)/ãç¨æ¼å代(replace)ç話ï¼åæ¯ç¨ $1, $2,...,$nãå¦ 'bar boo'.replace(/(...) (...)/, '$2 $1'). $&
表示已å¹é
çå串 (?:x)
Non-Capturing Parenthesesæ¾åº 'x'ï¼éåä½ä¸æè¨æ¶ ()
çº group çææï¼æª¢æ¥ææå wrap 䏿¬¡ï¼è¥æ g
flag æç¡æï¼ ?:
代表åªè¦ group 就好ï¼ä¸è¦ wrap æç¡ ()
å·®å¥ ï¼ 'foo'.match(/(foo)/)
// ['foo', 'foo', index: 0, input: 'foo' ] 'foo'.match(/foo/) // [ 'foo', index: 0, input: 'foo' ]
æç¡?:
å·®å¥ï¼ 'foo'.match(/(foo){1,2}/) // [ 'foo', 'foo', index: 0, input: 'foo' ] 'foo'.match(/(?:foo){1,2}/) [ 'foo', index: 0, input: 'foo' ]
é£()
齿²æï¼å{1,2}
åªæ¯é©ç¨å¨foo
ç第äºåo
çæ¢ä»¶èå·²ãæ´å¤è³è¨è©³è¦ä½¿ç¨æ¬èã x(?=y)
符å'x'ï¼ä¸å¾æ¥çæ¯'y'ã'y'çº'x'åå¨çæç¾©ã ä¾å¦ï¼/Jack(?=Sprat)/ï¼
å¨å¾é¢æ¯ Sprat çåå¨ä¸ï¼Jack æææç¾©ã /Jack(?=Sprat|Frost)/
å¾é¢æ¯ Spratãæè
æ¯ãFrost çåå¨ä¸ï¼Jack æææç¾©ã使åè¦æ¾çç®æ¨æ¯ Jackï¼å¾é¢çæ¢ä»¶é½åªæ¯ filter/æ¢ä»¶çåè½èå·²ã x(?!y)
符å'x'ï¼ä¸å¾æ¥ç䏿¯'y'ã'y'çºå¦å®'x'åå¨çæç¾©ï¼å¾é¢ä¸è¡ååç¡æ£(negated lookahead)ã ä¾å¦ï¼ /\d+(?!\.)/
ï¼è¦æ¾ä¸åæå¤åæ¸åæï¼å¨å¾é¢æ¥ç䏿¯ãé»ãçæ
æ³ä¸æç«ã var result = /\d+(?!\.)/.exec("3.141")
ï¼ result å·è¡åºä¾çº[ '141', index: 2, input: '3.141']ï¼ index:2ï¼ä»£è¡¨ 141 å¾ index = 2 éå§ã x|y
符åãxãæãyããèä¾ä¾èªªï¼/green|red/
çè©±ï¼æå¹é
"green apple"
ä¸ç "green"
以å "red apple."
ç "red"
ã {n}
è¦å®ç¬¦è確åç¼ççæ¬¡æ¸ï¼n çºæ£æ´æ¸ä¾å¦ï¼/a{2}/
ç¡æ³å¨ "candy" æ¾å°ãä½ "caandy" è¡ï¼è¥åä¸²ææ 2 åä»¥ä¸ "caaandy" éæ¯åªæèªåé¢ 2 åã {n,m}
æå°æ¢ä»¶ï¼n çºè³å°ãm çºè³å¤ï¼å
¶ nãm ççºæ£æ´æ¸ãè¥æ m è¨å®çº 0ï¼åçº Invalid regular expressionãä¾å¦ï¼/a{1,3}/
ç¡æ³å¨ "cndy" å¹é
å°ï¼èå¨ "candy" ä¸ç第 1 å"a"符åï¼å¨ "caaaaaaandy" ä¸çå 3 å "aaa" 符åï¼éç¶æ¤ä¸²æè¨±å¤ aï¼ä½åªèªåé¢ 3 åã [xyz]
åå
çéåãæ¤æ ¼å¼æå¹é
䏿¬èå
§ææåå
, including escape sequencesãç¹æ®åå
ï¼ä¾å¦é»ï¼.
ï¼ åç±³åèï¼*
ï¼ï¼å¨åå
éåä¸ä¸å
·ç¹æ®æç¾©ï¼æä»¥ä¸éè½æãè¥è¦è¨ä¸ååå
ç¯åçéåï¼å¯ä»¥ä½¿ç¨æ©«ç· "-"
ï¼å¦ä¸ä¾æç¤ºï¼ [a-d]
çåæ¼ [abcd]ã
æå¹é
"brisket" ç "b" ã"city" ç 'c' â¦â¦çã è/[a-z.]+/
å /[\w.]+/
åå¯å¹é
å串 "test.i.ng" ã [^xyz]
bracket ä¸å¯«å
¥çåå
å°è¢«å¦å®ï¼å¹é
éåºç¾å¨ bracket ä¸ç符èã å¯ç¨ '-' ä¾çå®åå
çç¯åãä¸è¬ç´æ¥è¡¨éç符èé½å¯ä»¥ä½¿ç¨é種æ¹å¼ã[^abc]
å¯ä»¥å¯«ä½[^a-c]
. "brisket" 䏿¾å° 'r' ã"chop."䏿¾å° 'h'ã [\b]
å»ååéåå
(U+0008). (ä¸æè· \b æ··æ·) \b
å»åæåéçãA word boundary matches the position where a word character is not followed or preceded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero. (Not to be confused with [\b]
.)Examples: /\bm/
matches the 'm' in "moon" ; /oo\b/
does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character; /oon\b/
matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character; /\w\b\w/
will never match anything, because a word character can never be followed by both a non-word and a word character.Note: JavaScript's regular expression engine defines a specific set of characters to be "word" characters. Any character not in that set is considered a word break. This set of characters is fairly limited: it consists solely of the Roman alphabet in both upper- and lower-case, decimal digits, and the underscore character. Accented characters, such as "é" or "ü" are, unfortunately, treated as word breaks. \B
å»åéæåéçãThis matches a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. The beginning and end of a string are considered non-words.For example, /\B../
matches 'oo' in "noonday", and /y\B./
matches 'ye' in "possibly yesterday." \cX
Where X is a character ranging from A to Z. Matches a control character in a string.For example, /\cM/
matches control-M (U+000D) in a string. \d
å»åæ¸åï¼å¯«æ³çåæ¼ [0-9] ã
ä¾å¦ï¼/\d/
æ /[0-9]/
å¨ "B2 is the suite number." 䏿¾å° '2' \D
å»å鿏åï¼å¯«æ³çåæ¼ [^0-9]ã
ä¾å¦ï¼/\D/
æ/[^0-9]/
å¨ "B2 is the suite number." 䏿¾å° 'B' ã \f
Matches a form feed (U+000C). \n
Matches a line feed (U+000A). \r
Matches a carriage return (U+000D). \s
Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
.For example, /\s\w*/
matches ' bar' in "foo bar." \S
Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\\u1680u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]
.For example, /\S\w*/
matches 'foo' in "foo bar." \t
Matches a tab (U+0009). \v
Matches a vertical tab (U+000B). \w
å
嫿¸å忝èåºç·ï¼çåæ¼[A-Za-z0-9_]
ãä¾å¦ï¼ /\w/
符å 'apple'ä¸ç 'a' ã'$5.28 ä¸ç '5' 以å '3D' ä¸ç '3'ãFor example, /\w/
matches 'a' in "apple," '5' in "$5.28," and '3' in "3D." \W
å
å«"é"æ¸å忝èåºç·ï¼çåæ¼[^A-Za-z0-9_]
ãä¾å¦ï¼ /\W/
ææ¯ /[^A-Za-z0-9_]/
符å "50%." ä¸ç '%'For example, /\W/
or /[^A-Za-z0-9_]/
matches '%' in "50%." \n
å
¶ä¸ n æ¯ä¸åæ£æ´æ¸ï¼è¡¨ç¤ºç¬¬ n 忬èä¸çåå串å¹é
ï¼å
嫿¬èä¸çææçå串å¹é
ï¼ä¾å¦ï¼ /apple(,)\sorange\1/
符å "apple, orange, cherry, peach." ç 'apple, orange,' ãï¼ `\1` 表示第ä¸å partten ï¼ä¹å°±æ¯ `(,)`ï¼For example, /apple(,)\sorange\1/
matches 'apple, orange,' in "apple, orange, cherry, peach." \0
Matches a NULL (U+0000) character. Do not follow this with another digit, because \0<digits>
is an octal escape sequence. Instead use \x00
. \xhh
Matches the character with the code hh (two hexadecimal digits) \uhhhh
Matches the character with the code hhhh (four hexadecimal digits).
Escaping user input that is to be treated as a literal string within a regular expressionâthat would otherwise be mistaken for a special characterâcan be accomplished by simple replacement:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
The g after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches. It is explained in detail below in Advanced Searching With Flags.
ä½¿ç¨æ¬èParentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. Once remembered, the substring can be recalled for other use, as described in Using Parenthesized Substring Matches.
For example, the pattern /Chapter (\d+)\.\d*/
illustrates additional escaped and special characters and indicates that part of the pattern should be remembered. It matches precisely the characters 'Chapter ' followed by one or more numeric characters (\d
means any numeric character and +
means 1 or more times), followed by a decimal point (which in itself is a special character; preceding the decimal point with \ means the pattern must look for the literal character '.'), followed by any numeric character 0 or more times (\d
means numeric character, *
means 0 or more times). In addition, parentheses are used to remember the first matched numeric characters.
This pattern is found in "Open Chapter 4.3, paragraph 6" and '4' is remembered. The pattern is not found in "Chapter 3 and 4", because that string does not have a period after the '3'.
To match a substring without causing the matched part to be remembered, within the parentheses preface the pattern with ?:
. For example, (?:\d+)
matches one or more numeric characters but does not remember the matched characters.
Regular expressions are used with the RegExp
methods test
and exec
and with the String
methods match
, replace
, search
, and split
. These methods are explained in detail in the JavaScript reference.
exec
A RegExp
method that executes a search for a match in a string. It returns an array of information or null on a mismatch. test
A RegExp
method that tests for a match in a string. It returns true or false. match
A String
method that executes a search for a match in a string. It returns an array of information or null on a mismatch. search
A String
method that tests for a match in a string. It returns the index of the match, or -1 if the search fails. replace
A String
method that executes a search for a match in a string, and replaces the matched substring with a replacement substring. split
A String
method that uses a regular expression or a fixed string to break a string into an array of substrings.
When you want to know whether a pattern is found in a string, use the test
or search
method; for more information (but slower execution) use the exec
or match
methods. If you use exec
or match
and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, RegExp
. If the match fails, the exec
method returns null
(which coerces to false
).
In the following example, the script uses the exec
method to find a match in a string.
var myRe = /d(b+)d/g;
var myArray = myRe.exec("cdbbdbsbz");
If you do not need to access the properties of the regular expression, an alternative way of creating myArray
is with this script:
var myArray = /d(b+)d/g.exec("cdbbdbsbz"); // similar to "cdbbdbsbz".match(/d(b+)d/g); however,
// the latter outputs Array [ "dbbd" ], while
// /d(b+)d/g.exec('cdbbdbsbz') outputs Array [ "dbbd", "bb" ].
// See below for further info (CTRL+F "The behavior associated with the".)
If you want to construct the regular expression from a string, yet another alternative is this script:
var myRe = new RegExp("d(b+)d", "g");
var myArray = myRe.exec("cdbbdbsbz");
With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.
Results of regular expression execution. ç©ä»¶ Property or index 說æ ç¯ä¾myArray
The matched string and all remembered substrings. ['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']
index
The 0-based index of the match in the input string. 1
input
The original string. "cdbbdbsbz"
[0]
The last matched characters. "dbbd"
myRe
lastIndex
The index at which to start the next match. (This property is set only if the regular expression uses the g option, described in Advanced Searching With Flags.) 5
source
The text of the pattern. Updated at the time that the regular expression is created, not executed. "d(b+)d"
As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable. If you do, however, every occurrence is a new regular expression. For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression. For example, assume you have this script:
var myRe = /d(b+)d/g;
var myArray = myRe.exec("cdbbdbsbz");
console.log("The value of lastIndex is " + myRe.lastIndex);
// "The value of lastIndex is 5"
However, if you have this script:
var myArray = /d(b+)d/g.exec("cdbbdbsbz");
console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex);
// "The value of lastIndex is 0"
The occurrences of /d(b+)d/g
in the two statements are different regular expression objects and hence have different values for their lastIndex
property. If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.
Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, /a(b)c/
matches the characters 'abc' and remembers 'b'. To recall these parenthesized substring matches, use the Array
elements [1]
, ..., [n]
.
The number of possible parenthesized substrings is unlimited. The returned array holds all that were found. The following examples illustrate how to use parenthesized substring matches.
ä¸é¢éå script 以 replace()
æ¹æ³ç§»è½å串ä½ç½®ãå°æ¼è¦è¢«ç½®æçæåå
§å®¹ï¼ä»¥ $1
å $2
ä¾ä»£è¡¨å
å re éåè®æ¸è£¡é¢ï¼æ¾åºä¾ç¶ç¶ä¸ç
§é åºä¾è¡¨ç¤ºå
©ååå串ã
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
console.log(newstr);
// "Smith, John"
Advanced Searching With Flags
Regular expressions have five optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any order, and are included as part of the regular expression.
Flag Descriptiong
Global search. i Case-insensitive search. m Multi-line search. u unicode; treat a pattern as a sequence of unicode code points y Perform a "sticky" search that matches starting at the current position in the target string. See sticky
To include a flag with the regular expression, use this syntax:
or
var re = new RegExp("pattern", "flags");
Note that the flags are an integral part of a regular expression. They cannot be added or removed later.
For example, re = /\w+\s/g
creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.
var re = /\w+\s/g;
var str = "fee fi fo fum";
var myArray = str.match(re);
console.log(myArray);
// ["fee ", "fi ", "fo "]
You could replace the line:
with:
var re = new RegExp("\\w+\\s", "g");
and get the same result.
The behavior associated with the 'g
' flag is different when the .exec()
method is used. (The roles of "class" and "argument" get reversed: In the case of .match()
, the string class (or data type) owns the method and the regular expression is just an argument, while in the case of .exec()
, it is the regular expression that owns the method, with the string being the argument. Contrast str.match(re)
versus re.exec(str)
.) The 'g
' flag is used with the .exec()
method to get iterative progression.
var xArray;
while ((xArray = re.exec(str))) console.log(xArray);
// produces:
// ["fee ", index: 0, input: "fee fi fo fum"]
// ["fi ", index: 4, input: "fee fi fo fum"]
// ["fo ", index: 7, input: "fee fi fo fum"]
The m
flag is used to specify that a multiline input string should be treated as multiple lines. If the m
flag is used, ^
and $
match at the start or end of any line within the input string instead of the start or end of the entire string.
The following examples show some uses of regular expressions.
Changing the order in an input stringThe following example illustrates the formation of regular expressions and the use of string.split()
and string.replace()
. It cleans a roughly formatted input string containing names (first name last) separated by blanks, tabs and exactly one semicolon. Finally, it reverses the name order (last name first) and sorts the list.
// The name string contains multiple spaces and tabs,
// and may have multiple spaces between first and last names.
var names = "Orange Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ";
var output = ["---------- Original String\n", names + "\n"];
// Prepare two regular expression patterns and array storage.
// Split the string into array elements.
// pattern: possible white space then semicolon then possible white space
var pattern = /\s*;\s*/;
// Break the string into pieces separated by the pattern above and
// store the pieces in an array called nameList
var nameList = names.split(pattern);
// new pattern: one or more characters then spaces then characters.
// Use parentheses to "memorize" portions of the pattern.
// The memorized portions are referred to later.
pattern = /(\w+)\s+(\w+)/;
// Below is the new array for holding names being processed.
var bySurnameList = [];
// Display the name array and populate the new array
// with comma-separated names, last first.
//
// The replace method removes anything matching the pattern
// and replaces it with the memorized stringâthe second memorized portion
// followed by a comma, a space and the first memorized portion.
//
// The variables $1 and $2 refer to the portions
// memorized while matching the pattern.
output.push("---------- After Split by Regular Expression");
var i, len;
for (i = 0, len = nameList.length; i < len; i++) {
output.push(nameList[i]);
bySurnameList[i] = nameList[i].replace(pattern, "$2, $1");
}
// Display the new array.
output.push("---------- Names Reversed");
for (i = 0, len = bySurnameList.length; i < len; i++) {
output.push(bySurnameList[i]);
}
// Sort by last name, then display the sorted array.
bySurnameList.sort();
output.push("---------- Sorted");
for (i = 0, len = bySurnameList.length; i < len; i++) {
output.push(bySurnameList[i]);
}
output.push("---------- End");
console.log(output.join("\n"));
使ç¨ç¹æ®åå
é©è輸å
¥
In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid.
Within non-capturing parentheses (?:
, the regular expression looks for three numeric characters \d{3}
OR |
a left parenthesis \(
followed by three digits \d{3}
, followed by a close parenthesis \)
, (end non-capturing parenthesis )
), followed by one dash, forward slash, or decimal point and when found, remember the character ([-\/\.])
, followed by three digits \d{3}
, followed by the remembered match of a dash, forward slash, or decimal point \1
, followed by four digits \d{4}
.
The Change
event activated when the user presses Enter sets the value of RegExp.input
.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript">
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
function testInfo(phoneInput) {
var OK = re.exec(phoneInput.value);
if (!OK)
window.alert(
phoneInput.value + " isn't a phone number with area code!",
);
else window.alert("Thanks, your phone number is " + OK[0]);
}
</script>
</head>
<body>
<p>
Enter your phone number (with area code) and then click "Check". <br />The
expected format is like ###-###-####.
</p>
<form action="#">
<input id="phone" /><button
onclick="testInfo(document.getElementById('phone'));">
Check
</button>
</form>
</body>
</html>
page(Doc) not found /zh-TW/docs/Web/JavaScript/Guide/Text_formatting
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4