2015-05-13 25 views
0

我知道Javascript沒有後視功能,儘管圍繞它的方法有些,但它們都沒有幫助。匹配一個序列,除非它前面有另一個序列,正則表達式(Javascript)

我需要匹配任何字符序列,除非它前面有一個特定的序列並由另一個序列成功。

所以,用類似的句子:

The watchdoggy jumped up.

如果我想匹配所有的字母,除非它們被watch前面,併成功通過gy它應該返回The jumped up.

這裏的竅門是儘管如此,在Javascript中執行此操作。有任何想法嗎?

+0

只是一個比賽,或在一個字符串匹配的重複? –

+0

如果javascript有向後看,你會怎麼做? – Bergi

+0

如果只匹配以'watch'開頭並由'gy'成功的字母並替換爲空字符串,可以嗎? –

回答

1

如果您只需要在一個位置執行此操作,則兩個捕獲組將執行此操作。

作爲替代操作:

var rex = /^(.*?)(?:watch.*?gy ?)(.*?)$/; 
 
var str = "The watchdoggy jumped up."; 
 
var result = str.replace(rex, "$1$2"); 
 
snippet.log("Result with match: '" + result + "'"); 
 
result = "Test that not matching works correctly".replace(rex, "$1$2"); 
 
snippet.log("Result without match: '" + result + "'");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

由於只是一根火柴,重新組裝:

var str = "The watchdoggy jumped up."; 
 
var m = /^(.*?)(?:watch.*?gy ?)(.*?)$/.exec(str); 
 
var result; 
 
if (!m) { 
 
    // No match, take the whole string 
 
    result = str; 
 
} else { 
 
    // Match, take just the groups 
 
    result = m[1] + m[2]; 
 
} 
 
snippet.log("Result: '" + result + "'");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

+0

儘管如此,非捕獲組應該是可選的。 – Bergi

+0

@Bergi:沒有必要,它使事情變得複雜。 –

+0

但是如果輸入中沒有'watchdoggy',它就不會匹配任何東西(它應該匹配整個輸入)? – Bergi

0

可以使用如果你有一個以上的位置如下:

\b(?!watch(.*?)gy\b)\w+ //if you want to capture only words (\w) 

DEMO

更通用的一個:

(\b(?!watch(.*?)gy\b).*?\b)+ //captures everything except letters 
           // preceeded by 'watch' and succeeded by 'gy' 

DEMO

相關問題