在java中编写正则表达式代码

时间:2014-10-11 06:34:09

标签: java regex

请帮助我们,我想知道如何编写正则表达式代码。

假设一个文件包含3个句子

[hi Tom how are you.hey Andy its nice to see you.where is your wife Tom.] 

所以当我搜索Tom时,我希望程序打印出第一个和最后一个句子,如果我搜索Andy,程序应该只打印第二个句子。

我疯了,因为我所做的只是打印TomAndy。 这是我的代码:

 Pattern p =Pattern.compile("Tom\\w+")

4 个答案:

答案 0 :(得分:0)

如果我理解您的问题,您希望匹配Tom的2个句子和Andy的1个句子。你想要这样做:

String line = "hi Tom how are you.hey Andy its nice to see you.where is your wife Tom.";

String pattern = "[\\w\\s]*Tom[\\w\\s]*[\\.]?";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

while (m.find()) {
    System.out.println("Find: " + m.group(0));
}

输出:

Find: hi Tom how are you.
Find: where is your wife Tom.

答案 1 :(得分:0)

如果您是初学者,请尝试下面的代码。您可以通过在一次迭代中检查多个键/人名来提高效率。

public class Tommy {

    public static void main(String[] args) {

        String junk = "hi Tom how are you.hey Andy its nice to see you.where is your wife Tom.";
        System.out.println(junk);
        String [] rez = extractor(junk, "Tom");
        printArray(rez);

    }

    public static String[] extractor(String text, String key) {
        String[] parts = text.split("\\.");
        String[] rez = new String[parts.length];// Use an arraylist ?

        for (int i = 0; i < parts.length; i++) {
            if (parts[i].contains(key)) {
                rez[i] = parts[i];
            }
        }

        return rez;
    }

    public static void printArray(String[] ar) {

        for (int i = 0; i < ar.length; i++) {
            if (ar[i] != null) {
                System.out.println(ar[i]);
            }
        }

    }

}

答案 2 :(得分:0)

假设每个句子以"."结束,然后:

public List<String> findMatches(String string, String name) {
    List<String> result = new ArrayList<String>();
    Pattern p = Pattern.compile("[\\w\\s]*" + name + "[\\w\\s]*");    
    for (String s : string.split("\\.")) {
        Matcher m = p.matcher(s);
        if(p.matcher(s).matches())
            result.add(s);
    }
    return result;
}


String string = "hi Tom how are you. hey Andy its nice to see you. where is your wife Tom.";
System.out.println(findMatches(string, "Tom");
System.out.println(findMatches(string, "Andy");

答案 3 :(得分:0)

(?=[^.]*?\bTom\b[^.]*\.)([\w\s]+(?=\.))

Tom试试。对于Andy,用Andy替换Tom.See演示。

http://regex101.com/r/vR4fY4/10