【问题标题】:Combining regex, matching both, not either结合正则表达式,匹配两者,而不是任何一个
【发布时间】:2016-05-10 09:24:13
【问题描述】:

好的,我想组合两个正则表达式。在下面的示例中,我想提取仅包含指定字母的任何单词,然后在该列表中,仅提取带有另一个字母的单词,在此示例中为 r。

我已经阅读了这个论坛上的几篇文章。

一个例子是: Combining regular expressions in Javascript

他们说要将表达式与|、exp1|exp2 结合起来。这就是我所做的,但我得到了我不应该说的话。如何在下面的示例中组合r1 和r2?

感谢您的帮助。

//the words in list form.
var a = "frog dog trig srig swig strog prog log smog snog fig pig pug".split(" "),
//doesn't work, can we fix?
     r = /^[gdofpr]+$|[r]+/,
    //These work.
    r1 = /^[gdofpr]+$/,
    r2 = /[r]+/,
    //save the matches in a list.
    badMatch = [], 
    goodMatch = [];
//loop through a.
for (var i = 0; i < a.length; i++) {
    //bad, doesn't get what I want.
    if (a[i].match(r)) badMatch[badMatch.length] = a[i];
    //works, clunky. Can we combine these?
    if (a[i].match(r1) && a[i].match(r2)) goodMatch[goodMatch.length] = a[i];
} //i
alert(JSON.stringify([badMatch, goodMatch])); //just to show what we got.

我得到以下信息。

[
    ["frog", "dog", "trig", "srig", "strog", "prog"],
    ["frog", "prog"]]

再次感谢。

【问题讨论】:

  • javascript != java
  • 这是否意味着您需要获取仅包含^[gdofpr]+$ 中的字符并且还包含r 的所有单词? /^[gdofpr]*r[gdofpr]*$/?
  • 与| 组合将匹配其中一个,而不是两者。
  • 您是想解决这个特定的查询,还是想在一个表达式中任意“与”两个正则表达式?如果是前者,那么@Wiktor 给了你一个可行的答案。
  • 我认为为 ANDing 正则表达式提供通用解决方案是不可行的。有不同的场景:1)前瞻与(例如^(?!p1$)p2$),2)点匹配与(例如p1.*p2|p2.*p1),3)使用从p1和p2推导出的条件构建一个全新的正则表达式 - 也许更多。

标签: javascript regex


【解决方案1】:

要仅匹配包含g、d、o、f、p 和r 字符且还包含r 的字符串,请使用

/^[gdofpr]*r[gdofpr]*$/

参见regex 和 JS 演示:

var a = "frog dog trig srig swig strog prog log smog snog fig pig pug".split(" ");
var res = a.filter(x => /^[gdofpr]*r[gdofpr]*$/.test(x));
document.body.innerHTML = JSON.stringify(res, 0, 4);

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2020-06-23
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多