JavaScript - 正则表达式

创建正则表达式

var re = /ab+c/;

var re = new RegExp('ab+c');

编写正则表达式样式

简单样式

/abc/
/*
匹配字符串中,一同出现 abc 字符
*/

指定字符样式(大小写敏感)

\   类似转义字符;示例:/a\*/,匹配:“a*”字符串。

^   判定每行的起始位置;示例:/^A/,匹配:"An e",匹配值为:"A"。

$   判定每行的结束位置;示例:/t$/,匹配:"eart",匹配值为:"t"。

*   判定操作符前的表达式出现0次,或者多次,功能同:{0,};示例:/bo*/,匹配:"A ghost booooed",匹配值为:"boooo"。

+   判定操作符前的表达式出现1次,或者多次;功能同:{1,};示例:/a+/,匹配:"caaaaaaandy",匹配值为:"aaaaaaa"。

?   判定操作符前的表达式出现0次,或者1次;功能同:{0,1};示例:/e?le?/,匹配:"angel angle oslo",匹配值为:"el le l";此操作符,若紧跟在:* + ? {} 之后,那么这些操作符就只匹配一个字符;示例:/\d+/,匹配:"123abc",匹配值为:"123";/\d+?/,匹配值分别为:"1" "2" "3"。

.   匹配除换行符号之外的,其他单独的符号;示例:/.n/,匹配:"an on",匹配值为:"an on";"nay, an apple is on the tree",匹配值为:"an on",注意没有匹配"nay",由于此字符中"n"前没有出现字符。

(x)   捕获组;示例:/(foo) (bar) \1 \2/,匹配:"foo bar foo bar",匹配值为:"foo bar foo bar";"foo bar bar foo",无匹配值,因为捕获组出现顺序不符。"(foo)"表示捕获组,"\1"表示捕获组的顺序。

(?:x)   非捕获组;示例:/(?:foo){1,2}/,匹配:"foo bar foo bar",匹配值为:"foo foo"。

x(?=y)   匹配x表达式,仅当其后跟随着y表达式的时候;示例:/Jack(?=Sprat)/,匹配:"JackSprat",匹配值为:"Jack";"Jack Sprat",匹配值无,由于Jack后没有紧随Sprat;/Jack(?=Sprat|Frost)/,匹配:"JackSprat JackFrost",匹配值为:"Jack Jack"。

x(?!y)   匹配x表达式,仅当其后没有跟随着y表达式的时候;示例:/\d+(?!\.)/,匹配:"3.141",匹配值为:"141"。

x|y   匹配x表达式,或者y表达式(x表达式没有出现的时候);示例:/green|red/,匹配:"green apple","red apple",匹配值为:"green","red"。

{n}   匹配操作符前的表达式出现n次,N必须为确定的正整数;示例:/a{2}/,匹配:"candy","caandy","caaandy",匹配值为:"无匹配","aa","aa"。

{n,}   匹配操作符前的表达式出现n次,或者多次,N必须为确定的正整数;示例:/a{2,}/,匹配:"a","aa","aaa",,"aaaa"匹配值为:"无匹配","aa","aaa","aaaa"。

{n,m}   匹配操作符前的表达式出现n次,或者m次,N M必须为确定的正整数,n<=m;示例:/a{1,3}/,匹配:"cndy","candy","caandy","caaandy",匹配值为:"无匹配","a","aa","aaa"。

[xyz]   匹配方括号中指定的字符集合,可以使用连字符"-"来指定字符集合范围;示例:/[a-d]/同/[abcd]/,匹配:"city",匹配值为:"c";/[a-z.]+/同/[\w.]+/,"test.i.ng",匹配值为:"test.i.ng"。

[^xyz]   匹配方括号中指定的字符集合之外的字符,可以使用连字符"-"来指定字符集合范围;示例:/[^abc]/同/[^a-c]/,匹配:"brisket","chop",匹配值为:"r i s k e t","h o p"。

[\b]   匹配退格键字符(U+0008),必须用方括号包裹,注意不要同"\b"混淆;

\b   匹配单词的边界;示例:/\bm/,匹配:"moon",匹配值为:"m";/oo\b/,"无匹配";/oon\b/,"oon"。

\B   匹配非单词的边界;匹配位置为:字符串首字符之前;字符串结尾字符之后;两个单词字符之间;两个非单词字符之间;空白字符串。

\cX   X为A-Z之间的字符,匹配"CTRL+M(U+000D)"字符。

\d   匹配数字字符,相当于[0-9];示例:/\d/同/[0-9]/,匹配:"2 B2",匹配值为:"2 2"。

\B   匹配非数字字符,相当于[^0-9];示例:/\B/同/[^0-9]/,匹配:"2 B2",匹配值为:"B"。

\f   匹配(U+000C)。

\n   匹配换行(U+000A)。

\r   匹配回车(U+000D)。

\s   匹配空间字符,包含:space, tab, form feed, line feed,相当于:[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff];示例:/\s\w*/,匹配:"foo bar",匹配值为:" bar"。

\S   匹配空间字符之外的字符,相当于:[^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff];示例:/\S*/,匹配:"foo bar",匹配值为:"foo 'foo结尾的间隔' bar 'bar结尾的间隔'"。

\t   匹配水平制表符(U+0009)。

\v   匹配垂直制表符(U+000B)。

\w   匹配字母、数字、下划线,相当于:[A-Za-z0-9_];示例:/\w/,匹配:"apple $5.28 3D",匹配值为:"a p p l e 5 2 8 3 D"。

\W   匹配非单词字符,相当于:[^A-Za-z0-9_];示例:/\W/,匹配:"$5.28 50%",匹配值为:"$ . %"。

\n   当n为确定的正整数时,以为表达式从左至右的位置,指代分组位置;示例:/apple(,)\sorange\1/,匹配:"apple, orange, cherry, peach.",匹配值为:"apple, orange"。

\0   匹配NULL字符(U+0000),不要在其后跟随其他的数字,因为\0<digits>表示八进制,可以使用\x00替代。

\xhh   匹配十六进制字符(两个十六进制字符)。

\uhhhh   匹配十六进制字符(四个十六进制字符)。

\u{hhhh}   匹配Unicode型的四个十六进制字符。

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& 意为整个匹配的字符串
}
// 正则表达式后的'g',表示执行全局搜索

使用圆括号()

圆括号会把同模式匹配的字符,以组的形式截出。示例:"Chapter (\d+)\.\d*",匹配:"Open Chapter 444.3, paragraph 6",此时截出的组为:"444";若不想以组的形式截出,可以使用"?:","Chapter (?:\d+)\.\d*",此时就不会截出分组。

使用正则表达式

exec RegExp的方法,以正则表达式搜索字符串,若有匹配,返回值为数组形式的信息,若无匹配,返回值为null。

var regex1 = RegExp('foo*','g');
var str1 = 'table football, foosball';
var array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

test RegExp的方法,测试正则表达式是否匹配字符串,若有匹配,返回值为true,若无匹配,返回值为false。

var regex1 = RegExp('foo*');
var regex2 = RegExp('foo*','g');
var str1 = 'table football';

console.log(regex1.test(str1));
// expected output: true

console.log(regex1.test(str1));
// expected output: true

console.log(regex2.test(str1));
// expected output: true

console.log(regex2.test(str1));
// expected output: false

match String的方法,以正则表达式搜索字符串,若有匹配,返回值为数组形式的信息,若无匹配,返回值为null。

var paragraph = 'The quick brown fox jumped over the lazy dog. It barked.';
var regex = /[A-Z]/g;
var found = paragraph.match(regex);

console.log(found);
// expected output: Array ["T", "I"]

search String的方法,以正则表达式匹配字符串,如有匹配,返回值为匹配处的索引,若无匹配,返回值为-1。

var paragraph = 'The quick brown fox jumped over the lazy dog. If the dog barked, was it really lazy?';

// any character that is not a word character or whitespace
var regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// expected output: 44

console.log(paragraph[paragraph.search(regex)]);
// expected output: "."

replace String的方法,以正则表达式搜索字符串,使用传入的子字符串,替换匹配的子字符串。

var p = 'The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?';

var regex = /dog/gi;

console.log(p.replace(regex, 'ferret'));

// expected output: "The quick brown fox jumped over the lazy ferret. If the ferret reacted, was it really lazy?"

split String的方法,使用正则表达式或者固定的子字符串,将字符串切分为数组。

var str = 'The quick brown fox jumped over the lazy dog.';

var words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

var chars = str.split('');
console.log(chars[8]);
// expected output: "k"

var strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumped over the lazy dog."]

var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';

console.log(names);

var re = /\s*(?:;|$)\s*/;
var nameList = names.split(re);

console.log(nameList);
// [ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]

正则表达式搜索样式标识

g   全局搜索。

i   不区分大小写搜索。

m   多行搜索。

u   以Unicode序列搜索。

y   若有指定,那么发现匹配之后,其余行就不再进行搜索匹配。

// 定义样式
var re = /pattern/flags;
var re = new RegExp('pattern', 'flags');

var re = /\w+\s/g; // var re = new RegExp('\\w+\\s', 'g');
var str = 'fee fi fo fum';
var myArray = str.match(re);
console.log(myArray);
// ["fee ", "fi ", "fo "]
<!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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值