In Java, what regular expression would I use to match a string that has exactly one colon and makes sure that the colon appears before any whitespace?
For example, it should match these strings:
label: print "Enter input"
But: I still had the money.
ghjkdhfjkgjhalergfyujhrageyjdfghbg:
area:54
But not
label: print "Enter input:"
There was one more thing: I still had the money.
ghfdsjhgakjsdhfkjdsagfjkhadsjkhflgadsjklfglsd
area::54
If you use it with
matches(which requires to match the entire string), you could useWhich means: arbitrarily many non-
whitespace, non-:characters, then a:, then more arbitrarily many non-:characters.I’ve really only used two regex concepts: (negated) character classes and repetition.
If you want to require at least one character before or after
:, replace the corresponding*with+(as jlordo pointed out in a comment).