繁体   English   中英

Java Regex包含匹配的新行

[英]Java Regex is including new line in match

我正在尝试将正则表达式与我从网站获得的教科书定义相匹配。 定义总是带有一个新行后跟定义的单词。 例如:

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+)$会起作用,但似乎根本没有成功匹配这个词。 我一直在测试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()));
}

通过调整结果字符串可以很容易地解决这个问题,但如果我已经使用了正则表达式,那么这似乎是不必要的。

非常感谢所有帮助。 提前致谢!

尝试使用Pattern.MULTILINE选项

Pattern rgx = Pattern.compile("^(\\S+)$", Pattern.MULTILINE);

这会导致正则表达式识别字符串中的行分隔符,否则^$只匹配字符串的开头和结尾。

虽然这种模式没有区别,但Matcher.group()方法返回整个匹配,而Matcher.group(int)方法根据您指定的数字返回特定捕获组(...)的匹配。 您的模式指定了一个您想要捕获的捕获组。 如果您在模式中包含\\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()));
 }

只需更换:

String result = mtch.group();

通过:

String result = mtch.group(1);

这会将输出限制为捕获组的内容(例如(\\\\w+) )。

迟到的响应,但是如果你没有使用Pattern和Matcher,你可以在你的正则表达式字符串中使用这个替代DOTALL

(?s)[Your Expression]

基本上(?s)也告诉dot匹配所有字符,包括换行符

详细信息: http//www.vogella.com/tutorials/JavaRegularExpressions/article.html

尝试下一个:

/* 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"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM