JavascriptReference(4)- RegExp Objects

 

Brief:Regular expressions are a powerful tool for performing pattern matches in Strings in JavaScript. You can perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions
Context
1           Regular expressions introduction
1) 2 ways to define a regular expression : literal syntax var re5digit=/^/d{5}$/; the RegExp() constructor method var RegularExpression = new RegExp("pattern");
2)Example:
        var re5digit=/^/d{5}$/
l         ^ indicates the match start at the beginning of the string; 
l         /d indicates a digit character, {5}following it means that there must be 5 consecutive digit characters ;
l         $ indicates the match end at the end of the string;
 
2           Categories of Pattern Matching Characters
2.1)Position Matching

Symbol
Description
Example
 ^
Only matches the beginning of a string.
/^The/ matches "The" in "The night" by not "In The Night"
 $
Only matches the end of a string.
/and$/ matches "and" in "Land" but not "landing"
 /b
Matches any word boundary (test characters must exist at the beginning or end of a word within the string)
/ly/b/ matches "ly" in "This is really cool."
 /B
Matches any non-word boundary.
//Bor/ matches “or” in "normal" but not "origami."

 
2.2)Literals

Symbol
Description
Alphanumeric
All alphabetical and numerical characters match themselves literally. So /2 days/ will match "2 days" inside a string.
 /n
Matches a new line character
 /f
Matches a form feed character
 /r
Matches carriage return character
 /t
Matches a horizontal tab character
 /v
Matches a vertical tab character
 /xxx
Matches the ASCII character expressed by the octal number xxx.

"/50" matches left parentheses character "("
 /xdd
Matches the ASCII character expressed by the hex number dd.

"/x28" matches left parentheses character "("
 /uxxxx
Matches the ASCII character expressed by the UNICODE xxxx.

"/u00A3" matches "£".

Notice: The backslash (/) is also used when you wish to match a special character literally. For example, if you wish to match the symbol "$" literally instead of have it signal the end of the string, backslash it: //$/ 
2.3)Character Classes

Symbol
Description
Example
 [xyz]
Match any one character enclosed in the character set. You may use a hyphen to denote range. For example. /[a-z]/ matches any letter in the alphabet, /[0-9]/ any single digit.
/[AN]BC/ matches "ABC" and "NBC" but not "BBC" since the leading “B” is not in the set.
 [^xyz]
Match any one character not enclosed in the character set. The caret indicates that none of the characters
NOTE: the caret used within a character class is not to be confused with the caret that denotes the beginning of a string. Negation is only performed within the square brackets.
/[^AN]BC/ matches "BBC" but not "ABC" or "NBC".
 .
(Dot). Match any character except newline or another Unicode line terminator.
/b.t/ matches "bat", "bit", "bet" and so on.
 /w
Match any alphanumeric character including the underscore. Equivalent to [a-zA-Z0-9_].
//w/ matches "200" in "200%"
 /W
Match any single non-word character. Equivalent to [^a-zA-Z0-9_].
//W/ matches "%" in "200%"
 /d
Match any single digit. Equivalent to [0-9].
 
 /D
Match any non-digit. Equivalent to [^0-9].
//D/ matches "No" in "No 342222"
 /s
Match any single space character. Equivalent to [ /t/r/n/v/f].
 
 /S
Match any single non-space character. Equivalent to [^ /t/r/n/v/f].
 

 
2.4)Repetition

Symbol
Description
Example
{x}
Match exactly x occurrences of a regular expression.
//d{5}/ matches 5 digits.
{x,}
Match x or more occurrences of a regular expression.
//s{2,}/ matches at least 2 whitespace characters.
{x,y}
Matches x to y number of occurrences of a regular expression.
//d{2,4}/ matches at least 2 but no more than 4 digits.
?
Match zero or one occurrences. Equivalent to {0,1}.
/a/s?b/ matches "ab" or "a b".
*
Match zero or more occurrences. Equivalent to {0,}.
/we*/ matches "w" in "why" and "wee" in "between", but nothing in "bad"
+
Match one or more occurrences. Equivalent to {1,}.
/fe+d/ matches both "fed" and "feed"

 
2.5)Alternation & Grouping

Symbol
Description
Example
( )
Grouping characters together to create a clause. May be nested.
/(abc)+(def)/ matches one or more occurrences of "abc" followed by one occurrence of "def".
|
Alternation combines clauses into one regular expression and then matches any of the individual clauses. Similar to "OR" statement.
/(ab)|(cd)|(ef)/ matches "ab" or "cd" or "ef".

2.6) Pattern Switches
In addition to the pattern-matching characters, you can use switches to make the match global or case- insensitive or both: Switches are added to the very end of a regular expression.

Property
Description
Example
 i
Ignore the case of characters.
/The/i matches "the" and "The" and "tHe"
 g
Global search for all occurrences of a pattern
/ain/g matches both "ain"s in "No pain no gain", instead of just the first.
 gi
Global search, ignore case.
/it/gi matches all "it"s in "It is our IT department" 

2.7) 正则表达式语法
一个正则表达式就是由普通字符(例如字符 a z )以及特殊字符(称为元字符)组成的文字模式。该模式描述在查找文字主体时待匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。
这里有一些可能会遇到的正则表达式示例:

JScript
VBScript
匹配
/^/[ /t]*$/
"^/[ /t]*$"
匹配一个空白行。
//d{2}-/d{5}/
"/d{2}-/d{5}"
验证一个 ID 号码是否由一个 2 位数字,一个连字符以及一个 5 位数字组成。
/<(.*)>.*<///1>/
"<(.*)>.*<///1>"
匹配一个 HTML 标记。

 
下表是元字符及其在正则表达式上下文中的行为的一个完整列表:

字符
描述
/
将下一个字符标记为一个特殊字符、或一个原义字符、或一个 后向引用、或一个八进制转义符。例如, 'n' 匹配字符 "n" '/n' 匹配一个换行符。序列 '//' 匹配 "/" "/(" 则匹配 "("
^
匹配输入字符串的开始位置。如果设置了 RegExp 对象的 Multiline 属性, ^ 也匹配 '/n' '/r' 之后的位置。
$
匹配输入字符串的结束位置。如果设置了 RegExp 对象的 Multiline 属性, $ 也匹配 '/n' '/r' 之前的位置。
*
匹配前面的子表达式零次或多次。例如, zo* 能匹配 "z" 以及 "zoo" * 等价于 {0,}
+
匹配前面的子表达式一次或多次。例如, 'zo+' 能匹配 "zo" 以及 "zoo" ,但不能匹配 "z" + 等价于 {1,}
?
匹配前面的子表达式零次或一次。例如, "do(es)?" 可以匹配 "do" "does" 中的 "do" ? 等价于 {0,1}
{n}
n 是一个非负整数。匹配确定的 n 次。例如, 'o{2}' 不能匹配 "Bob" 中的 'o' ,但是能匹配 "food" 中的两个 o
{n,}
n 是一个非负整数。至少匹配 n 次。例如, 'o{2,}' 不能匹配 "Bob" 中的 'o' ,但能匹配 "foooood" 中的所有 o 'o{1,}' 等价于 'o+' 'o{0,}' 则等价于 'o*'
{n,m}
m n 均为非负整数,其中 n <= m 。最少匹配 n 次且最多匹配 m 次。刘, "o{1,3}" 将匹配 "fooooood" 中的前三个 o 'o{0,1}' 等价于 'o?' 。请注意在逗号和两个数之间不能有空格。
?
当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串 "oooo" 'o+?' 将匹配单个 "o" ,而 'o+' 将匹配所有 'o'
.
匹配除 "/n" 之外的任何单个字符。要匹配包括 '/n' 在内的任何字符,请使用象 '[./n]' 的模式。
(pattern)
匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到,在 VBScript 中使用 SubMatches 集合,在 JScript 中则使用 $0$9 属性。要匹配圆括号字符,请使用 ' /(' ' /)'
(?:pattern)
匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用 " " 字符 (|) 来组合一个模式的各个部分是很有用。例如, 'industr(?:y|ies) 就是一个比 'industry|industries' 更简略的表达式。
(?=pattern)
正向预查,在任何匹配 pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如, 'Windows (?=95|98|NT|2000)' 能匹配 "Windows 2000" 中的 "Windows" ,但不能匹配 "Windows 3.1" 中的 "Windows" 。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。
(?!pattern)
负向预查,在任何不匹配 Negative lookahead matches the search string at any point where a string not matching pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如 'Windows (?!95|98|NT|2000)' 能匹配 "Windows 3.1" 中的 "Windows" ,但不能匹配 "Windows 2000" 中的 "Windows" 。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始
x |y
匹配 x y 。例如, 'z|food' 能匹配 "z" "food" '(z|f)ood' 则匹配 "zood" "food"
[xyz]
字符集合。匹配所包含的任意一个字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'
[^xyz]
负值字符集合。匹配未包含的任意字符。例如, '[^abc]' 可以匹配 "plain" 中的 'p'
[a-z]
字符范围。匹配指定范围内的任意字符。例如, '[a-z]' 可以匹配 'a' 'z' 范围内的任意小写字母字符。
[^a-z]
负值字符范围。匹配任何不在指定范围内的任意字符。例如, '[^a-z]' 可以匹配任何不在 'a' 'z' 范围内的任意字符。
/b
匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er/b' 可以匹配 "never" 中的 'er' ,但不能匹配 "verb" 中的 'er'
/B
匹配非单词边界。 'er/B' 能匹配 "verb" 中的 'er' ,但不能匹配 "never" 中的 'er'
/cx
匹配由 x 指明的控制字符。例如, /cM 匹配一个 Control-M 或回车符。 x 的值必须为 A-Z a-z 之一。否则,将 c 视为一个原义的 'c' 字符。
/d
匹配一个数字字符。等价于 [0-9]
/D
匹配一个非数字字符。等价于 [^0-9]
/f
匹配一个换页符。等价于 /x0c /cL
/n
匹配一个换行符。等价于 /x0a /cJ
/r
匹配一个回车符。等价于 /x0d /cM
/s
匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ /f/n/r/t/v]
/S
匹配任何非空白字符。等价于 [^ /f/n/r/t/v]
/t
匹配一个制表符。等价于 /x09 /cI
/v
匹配一个垂直制表符。等价于 /x0b /cK
/w
匹配包括下划线的任何单词字符。等价于 '[A-Za-z0-9_]'
/W
匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'
/xn
匹配 n ,其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如, '/x41' 匹配 "A" '/x041' 则等价于 '/x04' & "1" 。正则表达式中可以使用 ASCII 编码。 .
/num
匹配 num ,其中 num 是一个正整数。对所获取的匹配的引用。例如, '(.)/1' 匹配两个连续的相同字符。
/n
标识一个八进制转义值或一个后向引用。如果 /n 之前至少 n 个获取的子表达式,则 n 为后向引用。否则,如果 n 为八进制数字 (0-7) ,则 n 为一个八进制转义值。
/nm
标识一个八进制转义值或一个后向引用。如果 /nm 之前至少有 is preceded by at least nm 个获取得子表达式,则 nm 为后向引用。如果 /nm 之前至少有 n 个获取,则 n 为一个后跟文字 m 的后向引用。如果前面的条件都不满足,若   n m 均为八进制数字 (0-7) ,则 /nm 将匹配八进制转义值 nm
/nml
如果 n 为八进制数字 (0-3) ,且 m l 均为八进制数字 (0-7) ,则匹配八进制转义值 nml
/un
匹配 n ,其中 n 是一个用四个十六进制数字表示的 Unicode 字符。例如, /u00A9 匹配版权符号 (?)

 
3           String object has four methods that take regular expressions as arguments
   3.1)String Methods Using Regular Expressions

Method
Description
match( regular expression )
Executes a search for a match within a string based on a regular expression. It returns an array of information or null if no match are found.
Note: Also updates the $1…$9 properties in the RegExp object.
replace( regular expression, replacement text )
Searches and replaces the regular expression portion (match) with the replaced text instead.
Note: Also supports the replacement of regular expression with the specified RegExp $1…$9 properties.
split ( string literal or regular expression )
Breaks up a string into an array of substrings based on a regular expression or fixed string.
search( regular expression )
Tests for a match in a string. It returns the index of the match, or -1 if not found. Does NOT support global searches (ie: "g" flag not supported).

 
3.2)Example about String object’s Reg argument
var string1="Peter has 8 dollars and Jane has 15"
parsestring1=string1.match(//d+/g) //returns the array [8,15]
var string2="(304)434-5454"
parsestring2=string2.replace(/[/(/)-]/g, "") //Returns "3044345454" (removes "(", ")", and "-")
var string3="1,2, 3, 4,   5"
parsestring3=string3.split(//s*,/s*/) //Returns the array ["1","2","3","4","5"]
4 RegExp methods and properties
the Regular Expression (RegExp) object itself also supports two methods that mimic the functions of their string counterparts, the difference being these two methods take strings as parameters, while with String functions, they take a RegExp instead. The following describes the methods and properties of the regular expression object.
4.1)Methods

Method
Description
test(string)
Tests a string for pattern matches. This method returns a Boolean that indicates whether or not the specified pattern exists within the searched string. This is the most commonly used method for validation. It updates some of the properties of the parent RegExp object following a successful search.
exec(string)
Executes a search for a pattern within a string. If the pattern is not found, exec() returns a null value. If it finds one or more matches it returns an array of the match results. It also updates some of the properties of the parent RegExp object.

Here is a simple example that uses test() to see if a regular expression matches against a certain string:
var pattern=/php/i
pattern.test("PHP is your friend") //returns true
4.2)RegExp instance properties
要将全局 RegExp 对象与 正则表达式 对象混淆。尽管听起来像是一回事,但它们是截然不同的。全局 RegExp 对象的属性包含不断更新的关于每个匹配出现的信息,而正则表达式对象只包含出现正则表达式匹配的信息。 Whenever you define an instance of the regular expression (whether using the literal or constructor syntax), additional properties are exposed to this instance which you can use:
Properties

Property
Description
$n
n represents a number from 1 to 9
Stores the nine most recently memorized portions of a parenthesized match pattern. For example, if the pattern used by a regular expression for the last match was /(Hello)(/s+)(world)/ and the string being searched was “Hello world” the contents of RegExp.$2 would be all of the space characters between “Hello” and “world”.
source
Stores a copy of the regular expression pattern.
global
Read-only Boolean property indicating whether the regular expression has a "g" flag.
ignoreCase
Read-only Boolean property indicating whether the regular expression has a "i" flag.
lastIndex
Stores the beginning character position of the last successful match found in the searched string. If no match was found, the lastIndex property is set to –1.

This simple example shows how to determine whether a regular expression has the "g" flag added:
var pattern=/php/g
alert(pattern.global) //alerts true
 
5)Some sample:
5.1) Example 1:
<script>
function matchDemo(){
   var s;                                // 声明变量。
   var re = new RegExp("d(b+)(d)","ig"); // 正则表达式样式。
   var str = "cwwwdbbdwwwwbadbBdadabsbdbbBdz";             // 将被查找的字符串。
   var arr = re.exec(str);               // 进行查找。
  s = "$1 returns: " + RegExp.$1 + "<p>";
   s += "$2 returns: " + RegExp.$2 + "<p>";
   s += "$3 returns: " + RegExp.$3 + "<p>";
   s += "input returns : " + RegExp.input + "<p>";
   s += "lastMatch returns: " + RegExp.lastMatch + "<p>";
   s += "leftContext returns: " + RegExp.leftContext + "<p>";
   s += "rightContext returns: " + RegExp.rightContext + "<p>";
   s += "lastParen returns: " + RegExp.lastParen + "/n";
   s+="source returns:"+ RegExp.source +"<p>";
   s+="lastIndex returns:"+RegExp.lastIndex;
   return(s);                            // 返回结果。
}
document.open();
document.write(matchDemo());
</script>
 
OutPut:
$1 returns: bb
$2 returns: d
$3 returns:
input returns : cwwwdbbdwwwwbadbBdadabsbdbbBdz
lastMatch returns: dbbd
leftContext returns: cwww
rightContext returns: wwwwbadbBdadabsbdbbBdz
lastParen returns: d source returns:undefined
lastIndex returns:8
 
5.2) Example 2:
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值