我知道Javascript沒有後視功能,儘管圍繞它的方法有些,但它們都沒有幫助。匹配一個序列,除非它前面有另一個序列,正則表達式(Javascript)
我需要匹配任何字符序列,除非它前面有一個特定的序列並由另一個序列成功。
所以,用類似的句子:
The watchdoggy jumped up.
如果我想匹配所有的字母,除非它們被watch
前面,併成功通過gy
它應該返回The jumped up.
這裏的竅門是儘管如此,在Javascript中執行此操作。有任何想法嗎?
我知道Javascript沒有後視功能,儘管圍繞它的方法有些,但它們都沒有幫助。匹配一個序列,除非它前面有另一個序列,正則表達式(Javascript)
我需要匹配任何字符序列,除非它前面有一個特定的序列並由另一個序列成功。
所以,用類似的句子:
The watchdoggy jumped up.
如果我想匹配所有的字母,除非它們被watch
前面,併成功通過gy
它應該返回The jumped up.
這裏的竅門是儘管如此,在Javascript中執行此操作。有任何想法嗎?
如果您只需要在一個位置執行此操作,則兩個捕獲組將執行此操作。
作爲替代操作:
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>
只是一個比賽,或在一個字符串匹配的重複? –
如果javascript有向後看,你會怎麼做? – Bergi
如果只匹配以'watch'開頭並由'gy'成功的字母並替換爲空字符串,可以嗎? –