以下正则表达式可以满足您的需求:
\bgoing(\s+\w+){0,3}\s+work\b
Java 版本的正则表达式:
^.*?\\bgoing(\\s+\\w+){0,3}\\s+work\\b.*$
Java 代码:
String re = "^.*?\\bgoing(\\s+\\w+){0,3}\\s+work\\b.*$";
String str = "I am going one two three work";
System.out.printf("Matches: %s%n", str.matches(re)); // true
str = "I am going one two three four work";
System.out.printf("Matches: %s%n", str.matches(re)); // false
更新:由于 OP 想要根据动词列表检查这一点,这里是一个非基于正则表达式的解决方案:
List<String> verbs = new ArrayList<String>(
Arrays.asList(new String[]{"have", "going", "leaving"}));
String[] arr = str.split("\\s+"); // split words
int i;
for (i=0; i<arr.length; i++) { // find word "work" and save the index
if (arr[i].equals("work"))
break;
}
boolean found = false;
for (int j=i-1; j>0 && j >= i-4; j--) { // go backwards and search your verbs
System.out.printf("Finding: %s%n", arr[j]);
if (verbs.contains(arr[j])) {
found = true; // found it, break now
break;
}
}
System.out.printf("Found: %s%n", found);