Tuesday, November 14, 2017

Can regex match a pattern only if that pattern appears exactly one time?

Take this example:
string1 = "aaxadfxasdf"

string2 = "asdfxadf"

string3 = "sadfas"
i need a pattern that matches x such that it returns a match for x only for string2.
-------------
^[a-wy-z]+x[a-wy-z]+$
I'm not sure if you are only expecting letters, or if symbols and numbers might be included before and after the x you want to match. If so, use [^x] instead of [a-wy-z], like so:
^[^x]+x[^x]+$
If you are also wanting to match x by itself, replace the + symbols with * like so:
^[a-wy-z]*x[a-wy-z]*$

------------
^[^x]*x[^x]*$
where the first ^ is the beginning of the line ($ is the end), but the other ^ mean the complement of the character set

No comments:

Post a Comment