1

我正在尝试在 Java 中构建一个正则表达式字符串。

例子

search - test

它应该匹配以下测试用例

1. The test is done
2. me testing now
3. Test
4. tEST
5. the testing
6. test now

我现在拥有的(不工作)

([a-z]+)*[t][e][s][t]([a-z]+)*

什么是正确的正则表达式代码?

4

4 回答 4

2

一种方法可以是您String#matches这样调用:

String search = "test";
String line = "The Testing";
boolean found = line.matches("(?i)^.*?" + Pattern.quote(search) + ".*$"); // true

这里(?i)用于忽略大小写匹配,Pattern.quote用于从search字符串中转义可能的正则表达式特殊字符。

于 2013-10-08T14:43:47.537 回答
1

试试 ((\w\s) (test)(\s\w) )。还与您正在搜索的字符串一起使用 toLower

String regex = "((\\w\\s)*(test)(\\s\\w)*)";
String text = "someTesTt";

Pattern pattern = Pattern.compile(regex)

Matcher matcher = pattern.matcher(text.toLowerCase());
if(matcher.find()) {
     // we have a match!
}
于 2013-10-08T14:45:16.020 回答
1

你也可以使用Pattern pattern = Pattern.compile(".*test.*", Pattern.CASE_INSENSITIVE);

于 2013-10-08T14:45:40.723 回答
1

test在不区分字母大小的情况下查找单词的正则表达式将是

(t|T)(e|E)(s|S)(t|T)
于 2013-10-08T14:46:09.550 回答