Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果Regex中的令牌之前有文章,则丢弃它们_Javascript_Regex - Fatal编程技术网

Javascript 如果Regex中的令牌之前有文章,则丢弃它们

Javascript 如果Regex中的令牌之前有文章,则丢弃它们,javascript,regex,Javascript,Regex,我希望我的正则表达式匹配“foo”和“bar”,但如果“foo”或“bar”以“a”、“an”或“the”开头,则不匹配 foo和bar不保证位于字符串的开头或结尾 示例匹配: "end of Foo." [1 Match: Foo] "end of bar." [1 Match: bar] "The foo and bar" [1 Match: bar] "foo bar" [2 Matches: foo, bar] 示例:没有匹配项: "foobar" "foofoo" "the foo"

我希望我的正则表达式匹配“foo”和“bar”,但如果“foo”或“bar”以“a”、“an”或“the”开头,则不匹配

foo
bar
不保证位于字符串的开头或结尾

示例匹配:

"end of Foo." [1 Match: Foo]
"end of bar." [1 Match: bar]
"The foo and bar" [1 Match: bar]
"foo bar" [2 Matches: foo, bar]
示例:没有匹配项:

"foobar"
"foofoo"
"the foo"
"a bar"
"andbar"
"the foo goes to a bar."
我想我可能不得不做一个消极的回顾?如果是这样的话,这是否可以转化为对JS可移植性的负面展望

我试过了

/(\bfoo\b |\bbar\b)(?!a(n))/igm

但这不起作用


非常感谢。

一种方法是测试您测试的每个字符串是否存在捕获组。模式必须包含您想要避免的情况(跳过字符串的这一部分)。捕获组包含允许的案例。例如:

/\b(?:(?:the |an? )(?:foo|bar)|(foo|bar))\b/gi
例如:

var re = /\b(?:(?:the |an? )(?:foo|bar)|(foo|bar))\b/gi;
var str = "the foo a bar FoO BAr";
var myArray;
var result = Array();
while ((myArray = re.exec(str)) !== null) {
    if (myArray[1]) { // <- test if the capture group is defined
        result.push(myArray[1]);
    }
}

console.log(result);
var re=/\b(?:(?:the | an?(:foo | bar)|(foo | bar))\b/gi;
var str=“foo a bar foo bar”;
var-myArray;
var result=Array();
while((myArray=re.exec(str))!==null){

如果(myArray[1]){//您可能会发现编写正则表达式来匹配向后拼写的单词,并在匹配之前反转字符串的字符顺序更容易。这样,您就可以使用
负向前看模拟
负向后看

因此,带有反向单词的正则表达式是:

/\b(?:oof|rab)\b(?!eht|n?a)/igm
可视化:

JavaScript是:

function ReverseString(str) {
    return str.split("").reverse().join("");
}

var myRegex = /\b(?:oof|rab)\b(?!eht|n?a)/igm;
var myString = "This is foo possibly";

alert( ReverseString(myString).match(myRegex) );

好主意,别忘了
the
foo
之间有一个空格。哈哈,好的ol JS和好主意。我现在实际上是为C编写的-JS是为了将来的可移植性,我可能需要翻译它,因此我将语言排除在标记之外。我确信我可以找到一个支持Unicode的C的反向函数ough[]!你应该在C#中有一个更完整的正则表达式实现,它支持
反向外观
,所以我只需要在C#中正常编写正则表达式,然后在将其移植到JavaScript时使用反向方法。那么这是否与文章匹配,但有一个空的捕获?我有点困惑于如何实现它这在联机解析器中是匹配的。@kjhf:联机正则表达式测试器不是测试这一点的好工具,因为模式将匹配包含foo或bar的每个字符串。最好测试代码示例。@kjhf:请注意,您可以使用单个正则表达式来完成这项工作,但您需要更高级的正则表达式引擎,如pcre或perl。我将其标记为be尽管反向正则表达式是一个不错的解决方案,但它仍然是可读性的最佳答案。