0

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

例如:

哈利·詹姆斯·波特也被称为波特先生。波特在憔悴中非常有名。哈利·詹姆斯·波特也称波特先生。

我需要找到哈利詹姆波特和波特先生之间的内容:

输出应该是

  1. 也被称为
  2. 也被称为

谁能帮我吗?

这是我的代码:

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));
        }
    }
}
4

3 回答 3

0

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

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

在这里测试

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

于 2013-02-06T11:02:50.957 回答
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();
    }
于 2013-02-07T05:12:56.420 回答
-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
于 2014-01-25T15:50:31.347 回答