Skip to content
Advertisement

regex certain character can exist or not but nothing after that

I’m new to regex and I’m trying to do a search on a couple of string.

I wanted to check if a certain character, in this case its “:” (without the quote) exist on the strings.

If : does not exist in the string it would still match, but if : exist there should be nothing after that only space and new line will be allowed.

I have this pattern, but it does not seem to work as I want it.

(.*)(:?s*n*)

Thank you.

Advertisement

Answer

If I understand your question correctly, ^[^:]*(:s*)?$

Let’s break this down a bit:

^ Starting anchor; without this, the match can restart itself every time it sees another colon, or non-whitespace following a colon.

[^:]* Match any number of characters that AREN’T colon characters; this way, if the entire string is non-colon characters, the string is treated as a valid match.

(:s*)? If at any point we do see a colon, all following characters must be white space until the end of the string; the grouping parens and following ? act to make this an all-or-nothing conditional statement.

$ Ending anchor; without this, the regex won’t know that if it sees a colon the following whitespace MUST persist until the end of the string.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement