2014-12-01 316 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/

相關問題