首页 > 正则表达式中写多个^$有作用吗?

正则表达式中写多个^$有作用吗?

下面的正则表达式:

re1=/abc$def/m;
re1.test("abc$def");//显然是false
re1.test("abc\ndef");//仍然是false
re2=/abc^def/m;
re3=/abc$^def/m;
re4=/^abc$^def$/m;

这样的正则表达式是什么意思?
在正则表达式中出现多次$^ 有作用吗?

如果没有作用为什么也不报错???


@wangsquirrel 的答案可能有一些疏漏的地方:摘自:MDN 的 Regular_Expressions:

  • ^ : Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.
  • 所以如果设置了m这个flag的话,那么^是可以匹配到换行之后的开头的:
/abc\n^def/m.test("abc\ndef");
true
  • 所以这里的^并不是匹配它自己,而是代表了下一行的开头。
  • $ : Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.
  • 同^,如果设置了multi-line的flag,$可以出现在换行符之前来匹配一行的结束:
/abc$\ndef/m.test("abc\ndef");
true
  • 对backslash的解释是:
  • \ : Matches according to the following rules:
  • A backslash that precedes a non-special character indicates that the next character is special and is not to >- be interpreted literally. For example, a 'b' without a preceding '\' generally matches lowercase 'b's wherever >- they occur. But a '\b' by itself doesn't match any character; it forms the special word boundary character.
  • A backslash that precedes a special character indicates that the next character is not special and should >- be interpreted literally. For example, the pattern /a/ relies on the special character '' to match 0 or more >- a's. By contrast, the pattern /a*/ removes the specialness of the '*' to enable matches with strings like
  • 'a*'.
  • Do not forget to escape \ itself while using the RegExp("pattern") notation because \ is also an escape
  • character in strings.

^与$是特殊字符,如果没有加backslash转义的话,那么他们一定是表示特殊意思的,所以如果你要匹配这个字符本身,请加上转义符:

/abc^d/.test('abc^d')
false
/abc^d/.test('abc\^d')
false
/abc\^d/.test('abc\^d')
true
/abc\^d/.test('abc^d')
true

题主给的例子无法匹配的根本原因是^与$是去匹配一行的开头和结尾,而不是匹配换行符,所以其实是你的正则本身就匹配不上,而不是出错了。

这是我的一点理解,欢迎探讨交流。


正则表达式中 &^只有在结尾和开头有特殊含义,在其余位置指标是他们自己。没有特殊含义!


^ 脱字字符表示匹配搜索字符中串的开始位置。
& 恰好相反,表示匹配搜索字符串中结尾位置。
m 多行匹配模式修正符
如 @shizhz 所说。当你有了 /m 时,说明你是希望多行匹配的,那么 re1.test("abc$def") 中的 re1 应该写成 /abc\$def/,无多行匹配的情形,不需要加上 /m
re1.test("abc\ndef") 中的 re1 则应该写成 /abc\n^def/m,因为现在有了 \n 代表换行,所以你需要用到 /m 进行多行匹配。而中间的 ^ 代表第二行的开始位置。
我前几天对正则做了一篇总结,题主不妨一阅:《正则表达式基础》

【热门文章】
【热门文章】