正则表达式相关的混乱

时间:2019-01-16 18:16:43

标签: javascript regex

我想使用JavaScript中使用的正则表达式从以下字符串中提取 mkghj.bmg pp.kp

avb@gh.lk mkghj.bmg ,,,,fsdsdf.fdfd pllk.kp sdfsdf.bb,,,, pp.kp

括起来的所有字符都需要忽略。 、、、、可能有多个实例,但是它们在字符串中将始终出现偶数次(也没有发生)。

此外,avb @ gh.lk也带有@符号,因此需要忽略

我想我要寻找的规则是-如果有一个点(。),则向前看然后向后看:-

  1. 如果点号包含在、、、内,则将其忽略
  2. 如果点之前有@,且点和@之间没有空格,请忽略它
  3. 在所有其他情况下,请在点的两侧捕获一组连续的字符(直到遇到空格)

我想出了此正则表达式,但这对您没有帮助

[^\, ]+([^@ \,]+\w+)[^\, ]+

3 个答案:

答案 0 :(得分:2)

通常来说(请注意捕获小组):

not_this | neither_this_nor_this | (but_this_interesting_stuff)


对于您的特定示例,这可能是

,,,,.*?,,,,|\S+@\S+|(\S+)

您需要检查组1是否存在,请参阅a demo on regex101.com


JS中,应为:

var myString = "avb@gh.lk mkghj.bmg ,,,,fsdsdf.fdfd pllk.kp sdfsdf.bb,,,, pp.kp";
var myRegexp = /,,,,.*?,,,,|\S+@\S+|(\S+)/g;
match = myRegexp.exec(myString);
while (match != null) {
    if (typeof(match[1]) != 'undefined') {
        console.log(match[1]);
    }
match = myRegexp.exec(myString);
}

答案 1 :(得分:0)

Regex

^[^ ]+ ([^ ]+) ,,,,.*,,,,\s+(.*)

说明

^ asserts position at start of a line
    Match a single character not present in the list below [^ ]+
    + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
      matches the character   literally (case sensitive)
      matches the character   literally (case sensitive)
    1st Capturing Group ([^ ]+)
        Match a single character not present in the list below [^ ]+
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
          matches the character   literally (case sensitive)
     ,,,, matches the characters  ,,,, literally (case sensitive)
    .* matches any character (except for line terminators)
        * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    ,,,, matches the characters ,,,, literally (case sensitive)
    \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    2nd Capturing Group (.*)
        .* matches any character (except for line terminators)

答案 2 :(得分:0)

您可以将,,,之间的字符串替换为”,然后分割并搜索@符号和过滤器。

let str = `avb@gh.lk mkghj.bmg ,,,,fsdsdf.fdfd pllk.kp sdfsdf.bb,,,, pp.kp`

let op = str.replace(/,,,.*?,,,,|/g,'').split(' ').filter(e=> !e.includes('@') && e );

console.log(op)