我正在尝试将正则表达式与从网站上获得的教科书定义相匹配。定义中总是有一个单词,后面跟着一行新的定义。例如:
Zither
Definition: An instrument of music used in Austria and Germany It has from thirty to forty wires strung across a shallow sounding board which lies horizontally on a table before the performer who uses both hands in playing on it Not to be confounded with the old lute shaped cittern or cithern
在我试图只得到单词(在本例中为"Zither")的过程中,我一直得到换行符。
我尝试了^(w+)s
和^(S+)s
,但运气不太好。我以为^(S+)$
可能会起作用,但这似乎根本不符合这个词。我一直在用卢布进行测试,http://rubular.com/r/LPEHCnS0ri;它似乎成功地以我想要的方式匹配了我的所有尝试,尽管事实上Java没有。
这是我的片段
String str = ...; //Here the string is assigned a word and definition taken from the internet like given in the example above.
Pattern rgx = Pattern.compile("^(\S+)$");
Matcher mtch = rgx.matcher(str);
if (mtch.find()) {
String result = mtch.group();
terms.add(new SearchTerm(result, System.nanoTime()));
}
这很容易通过修剪结果字符串来解决,但如果我已经在使用正则表达式,那么这似乎是不必要的。
我们非常感谢所有的帮助。提前感谢!
尝试使用Pattern.MULTILINE选项
Pattern rgx = Pattern.compile("^(\S+)$", Pattern.MULTILINE);
这会导致正则表达式识别字符串中的行分隔符,否则^
和$
只匹配字符串的开始和结束。
尽管此模式没有区别,但Matcher.group()
方法返回整个匹配,而Matcher.group(int)
方法根据指定的数字返回特定捕获组(...)
的匹配。您的模式指定了一个捕获组,这就是您想要捕获的。如果您在尝试编写时在Pattern中包含了s
,那么Matcher.group()
就会在其返回值中包含该空白。
对于正则表达式,第一组总是完整的匹配字符串。在您的情况下,您想要的是组1,而不是组0。
因此,将mtch.group()
更改为mtch.group(1)
应该可以做到这一点:
String str = ...; //Here the string is assigned a word and definition taken from the internet like given in the example above.
Pattern rgx = Pattern.compile("^(\w+)s");
Matcher mtch = rgx.matcher(str);
if (mtch.find()) {
String result = mtch.group(1);
terms.add(new SearchTerm(result, System.nanoTime()));
}
延迟响应,但如果您不使用Pattern和Matcher,则可以在正则表达式字符串中使用DOTALL
的替代方案
(?s)[Your Expression]
基本上(?s)
还告诉点匹配所有字符,包括换行
详细信息:http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
只需替换:
String result = mtch.group();
签字人:
String result = mtch.group(1);
这会将您的输出限制为捕获组的内容(例如(\w+)
)。
尝试下一个:
/* The regex pattern: ^(w+)r?n(.*)$ */
private static final REGEX_PATTERN =
Pattern.compile("^(\w+)\r?\n(.*)$");
public static void main(String[] args) {
String input = "Zithern Definition: An instrument of music";
System.out.println(
REGEX_PATTERN.matcher(input).matches()
); // prints "true"
System.out.println(
REGEX_PATTERN.matcher(input).replaceFirst("$1 = $2")
); // prints "Zither = Definition: An instrument of music"
System.out.println(
REGEX_PATTERN.matcher(input).replaceFirst("$1")
); // prints "Zither"
}