简体   繁体   English

我可以使用通配符来解决这个问题吗?

[英]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.我正在学习 Java,但我遇到了一个简单的问题,但我被卡住了。

I need to search a string for the text "bob", except the "o" can be any character.我需要搜索文本“bob”的字符串,除了“o”可以是任何字符。 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:您可以使用带有正确正则表达式的matches()方法:

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

Note that the regex must match the whole string to return true .请注意,正则表达式必须匹配整个字符串才能返回true

If you want to match the word "bob", you'll need "word boundaries":如果要匹配单词“bob”,则需要“单词边界”:

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:此正则表达式匹配以 'b' 开头和结尾的整个单词,其中包含以下任何字母数字(或下划线)字符:

\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 \\\\要为 Java 字符串转义这些,请将每个 \\ 更改为 \\\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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