2

我想使用正则表达式检查一个单词(动词)是否出现在句子的某个位置。

keyword is "work"
verb is "going"

如果动词出现在“工作”一词的 3 个单词(索引)之前,我希望它返回 True

第 1 句:"I am going to work"

第 2 句:"I am going to be work"

第一个句子返回True,因为动词是关键字前面的 1 个单词。

第二句返回True,因为动词是关键字前面的 2 个单词。

目前我知道matcher.start()返回单词首字母的索引,我怎样才能找到一个单词相对于整个句子的索引?

4

3 回答 3

3

以下正则表达式可以满足您的需求:

\bgoing(\s+\w+){0,3}\s+work\b

现场演示:http ://www.rubular.com/r/ReJ062yYnY

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);
于 2013-07-12T17:37:30.960 回答
1

Try this

 String w1 = "I am going to work";                                       
 String w2 = "I am going to be work";                                    
 Pattern p = Pattern.compile("\\bgoing\\b(\\s+\\w+){1,3}\\s+\\bwork\\b");
 Matcher m = p.matcher(w1);                                              
 Matcher m1 = p.matcher(w2);                                             
 if (m.find()) {                                                         
   System.out.println(true);                                           
 }                                                                       
 if (m1.find()) {                                                        
   System.out.println(true);                                           

  }                                                                       
于 2013-07-12T17:49:59.623 回答
0

像这样的正则表达式应该可以工作:

"going(\s(\w+)){2}work"
于 2013-07-12T17:33:52.310 回答