我想检查一个单词(动词)是否出现在使用正则表达式的句子的某个位置。
keyword is "work"
verb is "going"
如果动词出现在单词“work”的3个单词(索引)之前,我希望它返回True
句子1:"I am going to work"
和
句子2:"I am going to be work"
第一句话返回True
,因为动词是关键字前面的1个单词。
第二句返回True
,因为动词是关键字前面的2个字。
目前我知道matcher.start()
要返回单词起始字母的索引,如何找到相对于整个句子的单词索引?
答案 0 :(得分:3)
以下正则表达式可满足您的需求:
\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
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);
答案 1 :(得分:1)
试试这个
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);
}
答案 2 :(得分:0)
像这样的正则表达式应该有效:
"going(\s(\w+)){2}work"