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);
所以文本可能是“获取号码”、“获取号码”、“号码是多少”、“号码是多少”、“告诉我号码”、“给我号码”
我的代码适用于“获取号码”和“什么是号码” 其中“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();
参见 Java demo online .
图案看起来像
((?:tell me|g(?:et|ive me)|what(?:\s+i|')s)(?:\s+the)?\s+number)
^^^^^^^^^^^
请注意,我用 \s+
替换了空格以匹配任何 1+ 个空白字符,并使用 Pattern.CASE_INSENSITIVE
标志编译正则表达式以启用不区分大小写的匹配。我还添加了替代项以匹配输入字符串的更多变体。
参见 regex online demo .
关于android - 句子或问题的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49127008/