我正在尝试将正则表达式与我从网站获得的教科书定义相匹配.定义总是带有一个新行后跟定义的单词.例如:
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
Run Code Online (Sandbox Code Playgroud)
在我尝试获得单词(在本例中为"Zither")时,我不断获得换行符.
我尝试了两个^(\w+)\s,^(\S+)\s没有太多运气.我认为这可能^(\S+)$会起作用,但似乎根本没有成功匹配这个词.我一直在测试rubular,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()));
}
Run Code Online (Sandbox Code Playgroud)
通过调整结果字符串可以很容易地解决这个问题,但如果我已经使用了正则表达式,那么这似乎是不必要的.
非常感谢所有帮助.提前致谢!
尝试使用Pattern.MULTILINE选项
Pattern rgx = Pattern.compile("^(\\S+)$", Pattern.MULTILINE);
Run Code Online (Sandbox Code Playgroud)
这使得正则表达式识别线分隔符在字符串中,否则^和$只是匹配字符串的开始和结束.
虽然这种模式没有区别,但该Matcher.group()方法返回整个匹配,而该Matcher.group(int)方法(...)根据您指定的数字返回特定捕获组的匹配.您的模式指定了一个您想要捕获的捕获组.如果你\s按照你所编写的模式包含在你的模式中,那么它Matcher.group()会在返回值中包含该空格.