CodersSC
CodersSC

Reputation: 710

Regular Expression to match a sequence

I want a regeular expression to match a sequence. The sequence in which i want the regular expression to match is NP so to make sure all the way down the string that after the N there is a P and that before the P there is an N

1) NPNPNPNP = correct

2)NPNPPNP = incorrect

SORRY GUYS I MISSED ONE MORE PART FROM THE QUESTION THE 3RD MATCH WOULD BE

3)NNNPNPNNP = correct SO THERE CAN BE MANY N's but at the end of the N there has to be a P to follow like above

But i do not think my regular expression is correct, can someone show me where i am going wrong?

std::string a ("NPNPNPPN");
 boost::regex const string_matcher("\(NP\)*");
 if(boost::regex_match(a,string_matcher))
 {
     DCS_LOG_DEBUG("Yes it Matches ");
 }
 else
 {
     DCS_LOG_DEBUG("No it does not Match");
 }

Upvotes: 1

Views: 369

Answers (4)

deltree
deltree

Reputation: 3824

EDIT: updated per the requirements changes and comments & suggestions

^(N+P)+$

Here it is with some tests

Further reading on regular expressions http://www.regular-expressions.info/tutorial.html

Upvotes: 5

Mike Ryan
Mike Ryan

Reputation: 4374

For your revised question, where NP pairs consist of 1 or more N's always followed by a single P, the regex would be:

^(?:N+P)+$
  • That's a non-capturing parentheses (?:
  • Followed by 1 or more N's N+
  • Followed by a P: P
  • Close Parentheses, to allow us to match on NP type pairs: )
  • Followed by a + to ensure that atleast one NP type pair exists. (i.e. there must be something to match.
  • With the whole expression surrounded w/ ^ and + so that it's only NP type pairs.

And if you want it to be case-insensitive, add regex_constants::icase to the regex constructor.

Upvotes: 2

James Kanze
James Kanze

Reputation: 153929

With boost regular expressions, ^(?:[^NP]*NP)*[^NP]*$ should do the trick, I think. A sequence of anything other than N or P, followed by NP, repeated as often as possible, followed by anything other than an N or a P. Starting at the beginning of the text, and continuing until the end. (If no characters other than N and P are allowed, then ^(?:NP)*$ is all that is needed.)

This is using the default settings (Perl regular expressions, I think).

Upvotes: 0

Pulkit Goyal
Pulkit Goyal

Reputation: 5654

Try this

 boost::regex const string_matcher("^(NP)*$");

Upvotes: -1

Related Questions