[英]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.