Reputation: 129
I use Java for an app with a stream of strings input. I want a regex that could detect whether there is a single-letter word "C/c", but not just a letter "C/c" in a longer.
For instance:
I think this pattern should be like "*c*
", the former *
should not be letter, the latter *
should be one of , .; )!
or space.
I just get confused with the regex. I tried some pattern pattern like [^A-Za-z]{0,}c[\,\.\;\s]{0,}
, but it doesn't work yet.
Upvotes: 3
Views: 6630
Reputation: 749
Use \W
. \W
is non-word character.
\W[cC]\W
https://regex101.com/r/khvMQk/1
Upvotes: 1
Reputation: 8561
Use word boundary markers
String pattern = ".*\\b[Cc]\\b.*";
The \b
matches a word boundary, i.e., anything of letter next to non-letter.
You need the 2 backslashes to escape the backslash for Java.
The .*
in the beginning and end make sure that Java does not try to anchor the pattern at beginning and end of the input.
Upvotes: 4