regEx匹配包含一个l和三个w的字符串

时间:2018-02-21 08:49:42

标签: javascript regex

有没有办法在短暂而轻松的情况下匹配那些“<<<< match this”标记的字符串,而不会使用regEx直接与许多ORs纠缠在一起?或者使用多个regEx请求?

所以比赛应该有4个字符 - > 3x w和1x l

string = 
"wwww
lwlw
lwww  << match this
wlww  << match this
wwlw  << match this
wwwl  << match this
llll"

数据:

string = 
"wwww
lwlw
lwww
wlww
wwlw
wwwl
llll"

输出:

output = 
"lwww
wlww
wwlw
wwwl"

我相信在这种情况下最好与明显的一致。如果存在较短的正则表达式,我很好奇。

var str =
`wwww
lwlw
lwww
wlww
wwlw
wwwl
llll`;

str.match(/\bwlww\b|\blwww\b|\bwwlw\b|\bwwwl\b/g);

(4) ["lwww", "wlww", "wwlw", "wwwl"]

3 个答案:

答案 0 :(得分:2)

过滤吗?

&#13;
&#13;
var string = 
`wwww
lwlw
lwww
wlww
wwlw
wwwl
llll`;
var pattern = ["lwww","wlww","wwlw","wwwl"];

var vals = string.split(/\s/).filter(function(row) {
  row = row.trim();
  return pattern.indexOf(row)!=-1;
})
console.log(vals)
&#13;
&#13;
&#13;

没有模式数组:

&#13;
&#13;
var string = 
`wwww
lwlw
lwww
wlww
wwlw
wwwl
llll`;

var vals = string.split(/\s/).filter(function(row) {
  return "lwww"=== row.trim().split("").sort().join("");
})
console.log(vals)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果您对非正则表达式解决方案没问题,请尝试splitfilter

  

所以比赛应该有4个字符 - &gt; 3x w和1x l

替换lengthl后,您可以查看w

split 换行符的数据,然后filter除了那些不匹配的数据

&#13;
&#13;
var str =
`wwww
lwlw
lwww
wlww
wwlw
wwwl
llll`;
//this function checks if the length of string after replace is equal to length
var replChLen = (str, ch, length) => 
    str.replace( new RegExp( ch, "g" ), "" ).length == length;

//filter out the matches
var output = str.split( "\n" ) //split by line-break
   .filter( s => //iterate to filter
      replChLen(s, "l", s.length - 1) //check if after replacing l, length is reduced by 1
        && replChLen(s, "w", s.length - 3) ); //check if after replacing w, length is reduced by 3
console.log( output );
&#13;
&#13;
&#13;

答案 2 :(得分:0)

正确的答案是:

(?=(?:.*w){3})(?=(?:.*l)).{4}

请参阅H E R E