[英]regex to match this repeating pattern?
我可以用此正则表达式匹配字符串[ORG] someText
: /^\\[(ORG|PER|LOC)]\\s[^\\W_]+$/
var selectedText = "[ORG] dd"; if (selectedText.match(/^\\[(ORG|PER|LOC)]\\s[^\\W_]+$/)) { console.log("working"); }
输入文本可以在标签中包含任何内容,后跟任何单词。
现在,我的文字为: [ORG] Lorem [ORG] ipsum
(以空格结尾)
我试图通过将模式分组并用+
(一个或多个事件)重复它来匹配它。
这样: /^(\\[(ORG|PER|LOC)]\\s[^\\W_]\\s)+$/
但是,它不匹配。
基本上,它应该匹配:
[tag] sometext
[tag] sometext [tag2] someOtherText // ending with or without a space
因此,通常,它需要匹配a tag followed by a space and a word
的模式, a tag followed by a space and a word
。
它不应该匹配的是:
[tag] sometext someMoreText
[tag] sometext someMoreText [tag9]
[tag] [tag9] sometext someMoreText
它应该是:
/^(\[(ORG|PER|LOC)]\s[^\W_]+(?:\s|$))+$/
...也就是说,在空格和行尾边界之间添加一个替代(对于字符串中的最后一个模式,它并不以空格结尾)。
演示 还要注意,如果只需要检查字符串是否与该模式匹配,则String#match
方法实际上是一个替代品; 相反,您应该RegExp#text
:
var tagsPattern = /^(\[(ORG|PER|LOC)]\s[^\W_]+(\s|$))+$/;
if (tagsPattern.test(str)) {
// matches
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.