Java正则表达式在匹配中包含新行

Java正则表达式在匹配中包含新行,java,regex,Java,Regex,我试图将正则表达式与我从网站上获得的教科书定义相匹配。 定义总是在单词后面加一行新词,然后是定义。例如: 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 perform

我试图将正则表达式与我从网站上获得的教科书定义相匹配。 定义总是在单词后面加一行新词,然后是定义。例如:

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+)$
可能有用,但这似乎根本不符合这个词。我一直在测试红疹;这似乎成功地匹配了我想要的所有尝试,尽管事实上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)
方法根据指定的数字返回特定捕获组的匹配。您的模式指定了一个捕获组,这是您想要捕获的。如果您在编写所尝试的模式时在模式中包含了
\s
,则
Matcher.group()
将在其返回值中包含该空格。

请尝试下一个:

/* The regex pattern: ^(\w+)\r?\n(.*)$ */
private static final REGEX_PATTERN = 
        Pattern.compile("^(\\w+)\\r?\\n(.*)$");

public static void main(String[] args) {
    String input = "Zither\n 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"
}

对于正则表达式,第一组始终是完整的匹配字符串。在您的情况下,您需要的是组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()));
 }
只需替换:

String result = mtch.group();
作者:


这会将您的输出限制为(例如,
(\\w+
)的内容。

延迟响应,但如果您不使用模式和匹配器,则可以在正则表达式字符串中使用此选项

(?s)[Your Expression]
基本上,
(?s)
还告诉dot匹配所有字符,包括换行符


详细信息:

\s
\n
等匹配。这就成功了。谢谢,我没有意识到您必须指定多行。
(?s)[Your Expression]