Java Pattern.compile()引发异常
我使用正则表达式来查找一个字符串是否存在于一个书页中。下面是相同的代码Java Pattern.compile()引发异常,java,android,regex,string,pattern-matching,Java,Android,Regex,String,Pattern Matching,我使用正则表达式来查找一个字符串是否存在于一个书页中。下面是相同的代码 String regex = ".*\\b.{0}" + searchText + ".{0}.*\\b"; Pattern pattern = Pattern.compile(regex); pattern.matcher("This is the text area where I am trying to look for the particular text, which is in the
String regex = ".*\\b.{0}" + searchText + ".{0}.*\\b";
Pattern pattern = Pattern.compile(regex);
pattern.matcher("This is the text area where I am trying to look for the particular text, which is in the variable searchText. This text will have the string (222M) as part of this string. The find method should give me a true result even if I don't enter the closing brakect of the word. This is a multiline string").find()
意见:
- 案例1:当searchText=“(222M)”时
- 结果:找到字符串
- 案例2:当searchText=“(222M”//括号缺失时 我得到以下例外 索引22附近的regexp模式中的括号嵌套不正确: .\b.{0}(1110r.{0}.\b
^尝试引用
搜索文本字符串:
... + Pattern.quote(searchText) + ...
…因为它可能包含模式
保留字符,从而破坏您的模式
编辑…当它包含非闭合圆括号时会出现这种情况
编辑(二)
我不太确定你想用模式的部分来完成什么
在这种情况下,以下是两个工作示例:
- 对于文字匹配(
String.contains
应执行相同的操作)
- 对于非单词有界匹配,其中给定
字符串前面或后面的任何字符都是非单词字符
String searchText = "(222M";
String regex = Pattern.quote(searchText);
Pattern pattern = Pattern.compile(regex);
Pattern boundedPattern = Pattern.compile("(?<=\\W)" + regex + "(?=\\W)");
String input = "This is the text area where I am trying " +
"to look for the particular text, which is in the variable searchText. " +
"This text will have the string (222M) as part of this string. " +
"The find method should give me a true result even if I don't " +
"enter the closing brakect of the word. This is a multiline string";
Matcher simple = pattern.matcher(input);
Matcher bounded = boundedPattern.matcher(input);
if (simple.find()) {
System.out.println(simple.group());
}
if (bounded.find()) {
System.out.println(bounded.group());
}
最后一个音符
如果希望模式不区分大小写,可以将模式.Pattern.CASE_INSENSITIVE
作为初始化标志添加到模式
。请注意,可以删除与空字符串匹配的无效{0}
。我已经尝试了Pattern.quote(searchText),它会停止错误,但与结果不匹配,因此无法达到目的。大小写为小写。感谢您提供关于{0}的建议.@Zooter则您的模式
实际上与文本不匹配。您必须提供清晰的输入/输出示例-可能是在一个新问题中。我已编辑了该问题。希望这有助于理解问题。@Zooter我已查看了您的示例。当然,无法找到“搜索文本”,带引号或不带引号,使用您正在使用的模式。如果您要查找的文本确实是searchText
的内容,我可以向您展示一个更简单的模式。否则,您的第二个问题仍然不清楚。请帮助我使用该模式。我面临的问题是,当我搜索“(222M)”时我没有得到结果。引号只是用来表示searchText是一个字符串,因此您可以忽略它。感谢您的坚持和帮助。
(222M
(222M