我知道Javascript没有lookbehind功能,虽然有很多方法,但它们似乎没有任何帮助。
我需要匹配任何字符序列,除非它先于某个序列并且由另一个序列继续。
所以,用一句话来说:
The watchdoggy jumped up.
如果我想匹配所有字母,除非它们前面有watch
并且gy
成功,它应该返回The jumped up.
这里的诀窍是在Javascript中执行此操作。有任何想法吗?
答案 0 :(得分: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>
答案 1 :(得分:0)