Reputation: 710
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
Reputation: 3824
EDIT: updated per the requirements changes and comments & suggestions
^(N+P)+$
Further reading on regular expressions http://www.regular-expressions.info/tutorial.html
Upvotes: 5
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)+$
(?:
N+
P
)
+
to ensure that atleast one NP type pair exists. (i.e. there must be something to match.And if you want it to be case-insensitive, add regex_constants::icase
to the regex constructor.
Upvotes: 2
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