Java正则表达式将提供的单词与特殊字符匹配
我试图通过使用Java模式类来匹配字符串Java正则表达式将提供的单词与特殊字符匹配,java,regex,pattern-matching,Java,Regex,Pattern Matching,我试图通过使用Java模式类来匹配字符串 private boolean isMatch(String searchSentence, String matchWord) { String patternText = ".*\\b"; Pattern pattern = Pattern.compile(patternText + matchWord + "\\b.*",Pattern.CASE_INSENSITIVE); Matcher match
private boolean isMatch(String searchSentence, String matchWord) {
String patternText = ".*\\b";
Pattern pattern = Pattern.compile(patternText + matchWord + "\\b.*",Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(searchSentence);
return matcher.matches();
}
如果我有匹配字符串,该字符串不包含任何特殊字符,如({[etc]
我能找到“RANCH”,但不能找到“RANCH(EAGLEFORD)”
再举几个例子
在正则表达式中使用特殊字符({})的示例 String stringToSearch=“我正在尝试RANCH(EAGLEFORD)和RANCH{EAGLEFORD}的一些长字符串” 输出: 牧场(鹰堡)
RANCH{EAGLEFORD}如果您计划匹配未包含单词字符(字母、数字或下划线)的关键字,请使用
(?!\w)和(?!\w)
lookarounds,而不是\b
private boolean isMatch(String searchSentence, String matchWord) {
Pattern pattern = Pattern.compile("(?<!\\w)" + Pattern.quote(matchWord) + "(?!\\w)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(searchSentence);
return matcher.find();
}
不要忘记使用模式。引用您的文字字符串
最好使用Matcher#find
,因为您不需要初始/尾随*
,并且消除了与regex回溯机制相关的不必要开销。什么是示例输入?预期输出是什么?您想做什么?单词边界对您来说是什么?是“单词”仅仅是一块非空白字符?请注意,)
不是单词字符,它后面的\b
将要求在括号后面有一个单词字符。另一个问题是您需要使用模式。quote(matchWord)
。让我们尝试通过一个提示来澄清它:try模式。compile(!)?
private boolean isMatch(String searchSentence, String matchWord) {
Pattern pattern = Pattern.compile("(?<!\\w)" + Pattern.quote(matchWord) + "(?!\\w)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(searchSentence);
return matcher.find();
}
private boolean isMatch(String searchSentence, String matchWord) {
Pattern pattern = Pattern.compile("(?<!\\S)" + Pattern.quote(matchWord) + "(?!\\S)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(searchSentence);
return matcher.find();
}