Home > OS >  Regular expression to match a word that contains ONLY one colon
Regular expression to match a word that contains ONLY one colon

Time:04-09

I am new to regex, basically I'd like to check if a word has ONLY one colons or not.

If has two or more colons, it will return nothing. if has one colon, then return as it is. (colon must be in the middle of string, not end or beginning.

(1)

a:bc:de  #return nothing or error.
a:bc    #return a:bc

a.b_c-12/:a.b_c-12/ #return a.b_c-12/:a.b_c-12/

(2)

My thinking is, but this is seems too complicated.

^[^:]*(\:[^:]*){1}$
^[-\w.\/]*:[-\w\/.]*   #this will not throw error when there are 2 colons.

Any directions would be helpful, thank you!

CodePudding user response:

I saw this as a good opportunity to brush up on my regex skills - so might not be optimal but it is shorter than your last solution. Hope it helps!

This is the regex pattern: /^[^:]*:{1}[^:]*$/gm and these are the strings I am testing against: 'oneco:on' (match) and 'one:co:on', 'oneco:on:', ':oneco:on' (these should all not match)

To explain what is going on, the ^ matches the beginning of the string, the $ matches the end of the string.

The [^:] bit says that any character that is not a colon will be matched.

In summary, ^[^:] means that the first character of the string can be anything except for a colon, *:{1} means that any number of characters can come after and be followed by a single (hence the 1) colon. Lastly, [^:]*$ means that any number (*) of characters can follow the colon as long as they are not a colon.

To elaborate, it is because we specify the pattern to look for at the beginning and end of the string, surrounding the single colon we are looking for that only the first string 'oneco:on' is a match.

Clear as mud I hope!

CodePudding user response:

This will find such "words" within a larger sentence:

(?<= |^)[^ :] :[^ :] (?= |$)

See live demo.

If you just want to test the whole input:

^[^ :] :[^ :] $

To restrict to only alphanumeric, underscore, dashes, dots, and slashes:

^[\w./-] :[\w./-] $
  • Related