有没有办法在短暂而轻松的情况下匹配那些“<<<< 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"]
答案 0 :(得分:2)
过滤吗?
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;
没有模式数组:
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;
答案 1 :(得分:2)
如果您对非正则表达式解决方案没问题,请尝试split
和filter
所以比赛应该有4个字符 - &gt; 3x w和1x l
替换length
和l
后,您可以查看w
。
split
换行符的数据,然后filter
除了那些不匹配的数据
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;
答案 2 :(得分:0)