简体   繁体   中英

Is there a wildcard character I can use to solve this?

I'm learning Java and I have a simple problem but I'm stuck.

I need to search a string for the text "bob", except the "o" can be any character. Is there a wildcard character I can use, or another simpler method?

Thanks in advance

You can use the matches() method with the right regex:

if (str.matches(".*b.b.*"))

Note that the regex must match the whole string to return true .

If you want to match the word "bob", you'll need "word boundaries":

if (str.matches("(?i).*\\bb[a-z]b\\b.*"))

Note that the "case insensitive" flag has been added to allow any case to match.

This regex matches a whole word starting and ending with 'b' with any alpha-numeric (or underscore) character between:

\bb\wb\b

To match any lowercase letter between, use

\bb[a-z]b\b

To match any letter between, use

\bb[a-zA-Z]b\b

To escape these for Java strings, change each \\ to \\\\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM