请帮助我!我正在使用正则表达式用 Java 编写程序。我有很多句子结构。
给定句子 - “为艾哈迈德·穆罕默德医生撰写的《学习 Java》一书”或“最好的标题:为艾哈迈德·穆罕默德学习 Java”,等等。
这意味着:
(book) may be [the book or text: or (text)].
(for doctor ) may be [ for author or for or by or for doctor].
正则表达式是:
"(?<=(book| the book| \\ (\\)|\\:)) .*? (?=(for doctor| for| for author))"
输出:
我想提取(书)之后和(医生)之前的任何单词并将其命名为标题。并提取 (for doctor ) 之后的任何单词并将其命名为 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);
这个程序在运行时给我错误,我会从正则表达式中得到支持。
最佳答案
您缺少
)
。\\)
是一个逃脱的)
,所以(\\)|\\:)
被括号包围,并且(book| the book| \\ (\\)|\\:))
也是,但是然后(?<=
没有右括号。我很确定你不能在
Matcher::matches()
上使用环视功能。因为它尝试匹配整个字符串,所以环视将在字符串开头之前和字符串结尾之后查找。使用Matcher::find()
效果更好。括号中的所有内容都是组(环视组和非捕获组除外),因此组 1 是
(book| the book| \\ (\\)|\\:))
第 2 组是(\\)|\\:)
(book| the book| \\ (\\)|\\:))
(和for doctor|...
)实际上不需要放在括号中,因为环视括号就足够了。您的正则表达式中似乎有太多空格(它们是正则表达式的一部分,因此需要匹配它们)。
如果您对
for doctor|for|for author
使用前瞻功能部分,您将无法捕获作者。您根本不需要环顾四周。
这让我们:
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);
}
?:
只是一个非捕获组,没有它们,匹配将是相同的,但您必须使用 group(3)
和group(5)
而不是group(1)
和group(2)
.
关于java - 如何编写正则表达式以及如何在java中制作更多一组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15457492/