String regex ="((?:get|what is) number)";
Pattern pattern = Pattern.compile(regex);
String text ="what is the number";
Matcher matcher = pattern.matcher(text);
boolean flag= matcher.matches();
Log.i("===matches or not??","==="+flag);
所以文字可能是“获取数字”,“获取数字”,“数字是什么”,“数字是什么”,“告诉我数字”,“给我号码”
我的代码适用于“get number”和“what is number”,其中“the”是可选的。而且我无法在上面的正则表达式中添加“作为可选字段”
因此,如果我输入“数字是什么”,那么它将返回false。
您可以添加一个带有单词(?:\s+the)?
的可选组:
String regex ="((?:tell me|g(?:et|ive me)|what(?:\\s+i|')s)(?:\\s+the)?\\s+number)";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
String text ="what is the number";
Matcher matcher = pattern.matcher(text);
boolean flag= matcher.matches();
图案看起来像
((?:tell me|g(?:et|ive me)|what(?:\s+i|')s)(?:\s+the)?\s+number)
^^^^^^^^^^^
注意我用\s+
替换空格以匹配任何1+空格字符,并使用Pattern.CASE_INSENSITIVE
标志编译正则表达式以启用不区分大小写的匹配。我还添加了替代方案来匹配输入字符串的更多变体。