Rahul Desai
Rahul Desai

Reputation: 15481

regex to match this repeating pattern?

I was able to match the string [ORG] someText with this regex: /^\[(ORG|PER|LOC)]\s[^\W_]+$/

var selectedText = "[ORG] dd";

if (selectedText.match(/^\[(ORG|PER|LOC)]\s[^\W_]+$/)) {
    console.log("working");
}

The input text could have anything in the tag followed by any word.


Now I have the text as: [ORG] Lorem [ORG] ipsum (ending with a space)

I tried to match this by grouping the pattern and repeating it with a + (one or more occurances).

This way: /^(\[(ORG|PER|LOC)]\s[^\W_]\s)+$/

However it doesnt match.

Basically, it should match:

[tag] sometext

[tag] sometext [tag2] someOtherText // ending with or without a space

So, in general, it needs to match a pattern of a tag followed by a space and a word.

What it shouldnt match:

[tag] sometext someMoreText

[tag] sometext someMoreText [tag9]

[tag] [tag9] sometext someMoreText 

Upvotes: 0

Views: 1461

Answers (1)

raina77ow
raina77ow

Reputation: 106375

It should be:

/^(\[(ORG|PER|LOC)]\s[^\W_]+(?:\s|$))+$/

... that is, adding an alternation between a whitespace and the end-of-line boundary (for the last pattern in the string doesn't end with a whitespace).

Demo. Also note that if you only need to check whether or not a string matches that pattern, String#match method is actually an overkill; instead you should RegExp#text:

var tagsPattern = /^(\[(ORG|PER|LOC)]\s[^\W_]+(\s|$))+$/;
if (tagsPattern.test(str)) {
  // matches 
}

Upvotes: 1

Related Questions