2014-12-01 129 views
-2

对不起,问这个愚蠢的问题,但我只是想确保我做对了。这两个正则表达式之间有什么区别

是什么

^Sentence.*$ 

^Sentence.* 

我通常使用的第一个,但我要确保这是比较合适的区别。

+1

[你明白'$'手段?](http://www.regular-expressions.info/anchors.html) – 2014-12-01 18:13:08

+0

他们是不一样的。 – 2014-12-01 18:13:15

+0

尝试regex101.com ... – vks 2014-12-01 18:13:36

回答

1

它取决于上下文(即字符串)。

$方式默认:字符串 而量词,像*端,由默认的贪婪。

如果字符串不包含换行符,则这两个模式完全相同。 (在这个意义上,他们将匹配完全相同的字符串)

但是,如果你的字符串包含换行符,该.*将收到停止,因为点,默认情况下,不换行字符相匹配。所以第一种模式总是会失败,第二种模式只会匹配第一行(如果它明显以“Sentence”开头)

+0

'$'匹配换行符前的*,因此两个正则表达式匹配完全相同,除非换行符后有任何*。 – 2014-12-01 18:25:27

+0

@TimPietzcker:并非所有的正则表达式,如果它对于PCRE或Python是正确的,对于ECMAScript或Ruby是错误的。 – 2014-12-01 18:41:30

0

来自RegExBuddy ;;

^ "Assert position at the beginning of a line (at beginning of the string or before a line break character)" 
. "Match any single character that is not a line break character" 
* "Between zero and unlimited times, as many times as possible, giving back as needed (greedy)" 
$ "Assert position at the end of a line (at the end of the string or before a line break character)" 

HTH。

http://www.regular-expressions.info/

相关问题