1

请帮我!我正在使用正则表达式用 Java 编写程序。我有很多句子结构。

给定句子 - “为 Ahmed Mohamed 医生写‘学习 java’ 的书”或“最好的书名:为 Ahmed Mohamed 学习 java”,等等。

这意味着:

(书)可以是[书或文本:或(文本)]。

(对于医生)可以是[为作者或为或由或为医生]。

正则表达式是:

"(?<=(book| the book| \\ (\\)|\\:)) .*? (?=(for doctor| for| for author))"

输出:

我想在(书)和(医生)之前提取任何单词并将其命名为标题。并在(对于医生)之后提取任何单词并将其命名为作者。

String inputtext =  "book 'learning java' for doctor  ahmed mohamed";
                                                 
Pattern p = Pattern.compile("(?<=(book| the book| \\ (\\)|\\:)) .*? (?=(for doctor| for| for author))");
    
Matcher m = p.matcher(inputtext);
    
    if (m.matches()) {
        String author = m.group(1).trim();
        String bookTitle = m.group(2).trim();
        
        System.out.println("Title is : " + author);
        System.out.println("Author is : " + bookTitle);
        

这个程序在运行时给了我错误,我会支持正则表达式。

4

1 回答 1

1
  1. 你缺少一个). \\)是一个转义的),所以(\\)|\\:)被括号包围,(book| the book| \\ (\\)|\\:))也是,但(?<=没有右括号。

  2. 我很确定您不能使用环视,Matcher::matches()因为它会尝试匹配整个字符串,因此环视将在字符串的开头和字符串的结尾之后查找。使用Matcher::find()效果更好。

  3. 括号中的所有内容都是组(环视组和非捕获组除外),因此第 1(book| the book| \\ (\\)|\\:))组是第 2 组(\\)|\\:)

  4. (book| the book| \\ (\\)|\\:))(and for doctor|...) 实际上不需要放在括号中,因为环视括号就足够了。

  5. 看来您的正则表达式中有太多空格(它们是正则表达式的一部分,因此需要匹配)。

  6. 如果您在for doctor|for|for author零件上使用前瞻,您将无法捕捉到作者。

  7. 你根本不需要环顾四周。

这使我们:

String inputtext =  "book 'learning java' for doctor  ahmed mohamed";
Pattern p = Pattern.compile("(book|\\)|\\:) (.*) for( doctor| author|) (.*)");
Matcher m = p.matcher(inputtext);
if (m.find()) {
    String title = m.group(2).trim();
    String author = m.group(4).trim();
    System.out.println("Title is : " + title);
    System.out.println("Author is : " + author);
}

如果您确实想使用匹配项:

String inputtext =  "book 'learning java' for doctor  ahmed mohamed";
Pattern p = Pattern.compile("(?:book|the book|(?:\\(.*?\\))|.*?\\:) (.*) for(?: doctor| author|) (.*)");
Matcher m = p.matcher(inputtext);
if (m.matches()) {
    String title = m.group(1).trim();
    String author = m.group(2).trim();

    System.out.println("Title is : " + title);
    System.out.println("Author is : " + author);
}

the?:只是一个非捕获组,没有它们匹配将是相同的,但您必须使用group(3)andgroup(5)而不是group(1)and group(2)

参考

于 2013-03-17T11:42:56.837 回答