使用java中的正则表达式搜索字符串

时间:2013-02-06 10:55:16

标签: java regex string search substring

我想知道如何检索字符串数组中存在的更多相似模式,无论字符串长度和存在多少这样的相似模式。

例如:

  

Harry James Potter也被称为Mr.Potter。波特非常有名。哈利詹姆斯波特也打电话给波特先生。

我需要找到Harry James Potter和Mr.Potter之间的内容:

输出应为

  1. 也称为
  2. 也叫
  3. 任何人都可以帮助我吗?

    这是我的代码:

    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class RegexTestHarness {
        public static void main(String[] args){
    
            String regex = "Harry James Potter (.*?) Mr.Potter";
    
            String strToSearch = "Harry James Potter also known as Mr.Potter. Harry       James Potter is famous as  Mr. Potter";
    
            Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    
            Matcher matcher = pattern.matcher(strToSearch);
    
            while (matcher.find()) {
    
                System.out.println("Text is at "+matcher.group()+"::"+matcher.start()+"::     "+matcher.end());
                System.out.println(matcher.groupCount());
    
                System.out.println(matcher.group(1));
            }
        }
    }
    

3 个答案:

答案 0 :(得分:0)

这个正则表达式将拾取“Harry James Potter”和“Mr.Potter”之间的任何内容:

Harry James Potter (.*?) Mr\.Potter

经过测试here

根据您的Regex实现,您可能需要检索结果组1。

答案 1 :(得分:0)

确保在编写正则表达式字符串时避开Mr.Potter中的句号。你的strToSearch也有随机空格,这会使你的正则表达不能找到你想要的东西。此代码生成您提供的示例。

try {
        String regex = "Harry James Potter (.*?) Mr\\.Potter";
        String strToSearch = "Harry James Potter also known as Mr.Potter. Potter is very famous in hagwards. Harry James Potter also called Mr.Potter.";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(strToSearch);
        int start = 0;
        int count = 1;
        while (matcher.find(start)) {
            System.out.println(count + ". " + matcher.group(1));
            start = matcher.end();
            count++;
        }

    } catch(Exception ex) {
        ex.printStackTrace();
    }

答案 2 :(得分:-1)

    String s = "Harry James Potter also known as Mr.Potter . Potter is very famous in hagwards. Harry James Potter also called Mr.Potter.";
    Pattern pattern = Pattern.compile("(?<=Harry James Potter )(.*?)(?= Mr.Potter)");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {            
        System.out.println(matcher.group(1));
    }

输出:

also known as
also called