[英]pattern matching to detect special characters in a word
I am trying to identify any special characters ('?', '.', ',') at the end of a string in java. 我正在尝试在Java字符串的末尾标识任何特殊字符(“?”,“。”,“,”)。 Here is what I wrote:
这是我写的:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("{.,?}$");
Matcher matcher = pattern.matcher("Sure?");
System.out.println("Input String matches regex - "+matcher.matches());
}
This returns a false
when it's expected to be true
. 如果预期为
true
,则返回false
。 Please suggest. 请提出建议。
Use "sure?".matches(".*[.,?]")
. 使用
"sure?".matches(".*[.,?]")
。
String#matches(...)
anto-anchors the regex with ^
and $
, no need to add them manually. String#matches(...)
使用^
和$
固定正则表达式,无需手动添加它们。
Try this 尝试这个
Pattern pattern = Pattern.compile(".*[.,?]");
...
This is your code: 这是您的代码:
Pattern pattern = Pattern.compile("{.,?}$");
Matcher matcher = pattern.matcher("Sure?");
System.out.println("Input String matches regex - "+matcher.matches());
You have 2 problems: 您有2个问题:
{ and }
instead of character class [ and ]
{ and }
而不是字符类[ and ]
Matcher#matches()
instead of Matcher#find
. Matcher#matches()
而不是Matcher#find
。 matches
method matches the full input line while find
performs a search anywhere in the string. matches
方法匹配完整的输入行,而find
在字符串中的任何位置执行搜索。 Change your code to: 将您的代码更改为:
Pattern pattern = Pattern.compile("[.,?]$");
Matcher matcher = pattern.matcher("Sure?");
System.out.println("Input String matches regex - " + matcher.find());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.