[英]Regex - Javascript capture area
I want to capture only a area of the Match part. 我只想捕获“匹配”部分的一个区域。 I have following String:
" type1-class1 type1-class2 type2-class4 type2-type1-class3 "
and i want following result ["class1", "class2"]
. 我有以下字符串:
" type1-class1 type1-class2 type2-class4 type2-type1-class3 "
,我想要以下结果["class1", "class2"]
。 I am searching the class by the type
. 我正在按
type
搜索课程。 I have tried following: 我尝试了以下方法:
console.log(" type1-class1 type1-class2 type2-class4 type2-type1-class3 ".match(/\\btype1-.*?(?= )/g)) // Result: ["type1-class1", "type1-class2", "type1-class3"]
Furthermore i have tried following: 此外,我尝试了以下方法:
console.log(" type1-class1 type1-class2 type2-class4 type2-type1-class3 ".match(/(?= type1-).*?(?= )/g)); // Result: ["", ""]
How can i disable the capture on the beginning of a Regex? 如何在正则表达式的开头禁用捕获?
I'd use an exec
loop. 我会使用
exec
循环。 The regular expression is /(?:^|\\s)type1-([^ ]+)/g
, eg, "Following a type-1
that's at the beginning of the string or just after whitespace, capture everything until the next whitespace or end of string. (With your string as given, we don't need the alternation with ^
, but I wanted to allow for "type1-class1"
at beginning of string.) We then collect the captures in a loop: 正则表达式为
/(?:^|\\s)type1-([^ ]+)/g
,例如,“跟随在字符串开头或紧跟空格之后的type-1
,捕获所有内容,直到下一个空格或字符串的结尾(给定您的字符串,我们不需要与^
交替,但我想在字符串的开头允许"type1-class1"
。)然后,我们在循环中收集捕获:
var rex = /(?:^|\\s)type1-([^ ]+)/g; var str = " type1-class1 type1-class2 type2-class4 type2-type1-class3 "; var classes = []; var m; while ((m = rex.exec(str)) != null) { classes.push(m[1]); } console.log(classes);
这是您所期望的吗?
console.log(" type1-class1 type1-class2 type2-class4 type2-type1-class3 ".match(/ type1-.*?(?= )/g).map(x=>x.replace(/type1-/g,"").trim()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.