如何在 Java 8 正则表达式中使用 \R

hap*_*dha 1 regex java-8

我正在尝试使用java 8 中新的\R正则表达式匹配器。但是,对于以下代码:

public static void main(String[] args)
  {
    String s = "This is \r\n a String with \n Different Newlines \r and other things.";
    System.out.println(s);
    System.out.println(Pattern.matches("\\R", s));
    if (Pattern.matches("\\R", s)) // <-- is always false
    {
      System.out.println("Matched");
    }

    System.out.println(s.replaceAll("\\R", "<br/>")); //This is a String with <br/> Different Newlines <br/> and other things.
  }
Run Code Online (Sandbox Code Playgroud)

Pattern.matches始终返回false,其中作为replaceAll方法似乎找到了比赛和做什么,我想它。如何使 Pattern.matches 工作?

我也试过很长的路,但仍然无法让它工作:

   Pattern p = Pattern.compile("\\R");
    Matcher m = p.matcher(s);
    boolean b = m.matches();
    System.out.println(b);
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 6

好吧matches(inStringMatchersclasses)尝试匹配完整的输入字符串。

您需要matcher.find改用:

Pattern p = Pattern.compile("\\R");
Matcher m = p.matcher(s);
boolean b = m.find();
System.out.println(b);
Run Code Online (Sandbox Code Playgroud)

来自Java 文档

\R 匹配任何 Unicode 换行符序列,相当于 \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

PS; 如果您想知道输入是否包含换行符,那么此一行代码对您有用:

boolean b = s.matches("(?s).*?\\R.*");
Run Code Online (Sandbox Code Playgroud)

注意.*在 的任一侧使用\R以确保我们匹配完整的输入。您还需要(?s)启用DOTALL模式才能将多行字符串与.*