我正在寻找一个正则表达式来检查字符串是否包含2个特定单词。例如该字符串是否包含公鸡或母鸡。
提前致谢!
答案 0 :(得分:19)
将rooster
或hen
与完整单词匹配的表达(即,当它们是较长的不同单词的一部分时):
\b(rooster|hen)\b
这是一种避免部分匹配误报的安全措施。
\b
表示a word boundary,它是“单词字符”([A-Za-z0-9_]
)范围内的字符与任何其他字符之间的(零宽度)点。实际上,上面会:
"A chicken is either a rooster or a hen."
"Chickens are either a roosters or hens."
中(rooster|hen)
会作为旁注,为了允许复数,这将做:\b(roosters?|hens?)\b
答案 1 :(得分:3)
使用|
替代方案。在你的情况下,它是:(rooster|hen)
答案 2 :(得分:2)
您没有提及您正在使用的引擎/语言,但通常情况下,正则表达式为(rooster|hen)
。 |
是alternation运营商。
答案 3 :(得分:1)
对我有用的是
(?:word|anotheer word)
这是一个使用我在我的应用程序http://regexr.com/3gjb2
中使用它的示例如果您有兴趣了解(?:
(
与 import java.util.*;
import java.lang.*;
import java.io.*;
// A class to represent a student.
class Student {
int rollno;
String name;
String address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString(){
return this.rollno + " " + this.name +
" " + this.address;
}
}
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of rollno
public int compare(Student a, Student b) {
return a.rollno - b.rollno;
}
}
class Sortbyname implements Comparator<Student> {
// Used for sorting in ascending order of name
public int compare(Student a, Student b) {
return a.name.compareTo(b.name);
}
}
// Driver class
class Main {
public static void main (String[] args) {
ArrayList<Student> ar = new ArrayList<Student>();
//here I have thousand student are inserted into
//simple collection.
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));
System.out.println("Unsorted");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
//collection sorted by rollno
Collections.sort(ar, new Sortbyroll());
System.out.println("\nSorted by rollno");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
//sort by Name
Collections.sort(ar, new Sortbyname());
System.out.println("\nSorted by name");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
}
}
的差异,请查看此问题
答案 4 :(得分:0)
我有一个类似的要求,但是它只能包含一个特定的单词(来自列表),并且字符串中不应包含其他单词。我不得不使用^(rooster|hen)$