如何为以下内容编写正则表达式?

时间:2013-12-07 01:03:24

标签: java

我想写一个正则表达式,以便我可以找到如下所有单词组: "{the cat}"所以正则表达式应匹配字符串"{the cat}"或任何字母数字字符,包括“:”?

1 个答案:

答案 0 :(得分:1)

以下内容与keys中的所有sentence相匹配。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public static void main(String[] args) {
    String sentence = "There is the cat";
    String[] keys = {"the", "cat"};        

    StringBuilder pattern = new StringBuilder("");
    for(String key: keys)
        pattern.append("\\b"+key+"\\b|");

    Pattern r = Pattern.compile(pattern.substring(0, pattern.length()-1));
    Matcher m = r.matcher(sentence);
    while(m.find())
        System.out.println("("+m.group()+", start:"+m.start()+", end:"+m.end()+")");
}

输出:

(the, start:9, end:12)
(cat, start:13, end:16)