[英]find two consecutive words/strings with regex expression java (including punctuation)
我想检查一个字符串是否包含两个单词/字符串,然后直接按照特定顺序进行。 标点符号也应包含在单词/字符串中。 (即, “单词”和“单词”。应作为不同的单词处理 )。
举个例子:
String word1 = "is";
String word1 = "a";
String text = "This is a sample";
Pattern p = Pattern.compile(someregex+"+word1+"someregex"+word2+"someregex");
System.out.println(p.matcher(text).matches());
这应该打印出true 。
使用以下变量,它也应该显示true。
String word1 = "sample.";
String word1 = "0END";
String text = "This is a sample. 0END0";
但是当设置word1 =“ sample”(不带标点符号)时,后者应返回false。
有谁知道正则表达式字符串应该是什么样子(即我应该写什么而不是“ someregex”?)
谢谢!
看起来您只是在空格上拆分,请尝试:
Pattern p = Pattern.compile("(\\s|^)" + Pattern.quote(word1) + "\\s+" + Pattern.quote(word2) + "(\\s|$)");
释
(\\\\s|^)
匹配第一个单词或字符串开头之前的任何空格
\\\\s+
匹配单词之间的空格
(\\\\s|$)
匹配第二个单词之后或字符串末尾的所有空格
Pattern.quote(...)
确保输入字符串中的任何正则表达式特殊字符都正确转义。
您还需要调用find()
,而不是match()
。 仅当整个字符串与模式匹配时, match()
才会返回true。
完整的例子
String word1 = "is";
String word2 = "a";
String text = "This is a sample";
String regex =
"(\\s|^)" +
Pattern.quote(word1) +
"\\s+" +
Pattern.quote(word2) +
"(\\s|$)";
Pattern p = Pattern.compile(regex);
System.out.println(p.matcher(text).find());
您可以将两个单词用空格连接起来,并将其用作正则表达式。 唯一要做的就是替换“。” 与“。” 因此该点与任何字符都不匹配。
String regexp = " " + word1 + " " + word2 + " ";
regexp = regexp.replaceAll("\\.", "\\\\.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.