Dong  Robbin
Dong Robbin

Reputation: 129

Regular expression for a single letter word

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

Answers (3)

Jobelle
Jobelle

Reputation: 2834

Try his

var pattern= /(\bC\b)/i;

https://regex101.com/r/gN5Z8Q/1

Upvotes: 0

Yeongjun Kim
Yeongjun Kim

Reputation: 749

Use \W. \Wis non-word character.

\W[cC]\W

https://regex101.com/r/khvMQk/1

Upvotes: 1

Robert
Robert

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

Related Questions