Regular expression for detecting round brackets

前端 未结 3 1789
夕颜
夕颜 2021-01-24 18:23

I have a large array with string. Now, I need to use the string in the array to form patterns. However for the string with round brackets, the constructed patterns don\'t work.

相关标签:
3条回答
  • 2021-01-24 18:53

    It should definitely work well... if you test against a matching String :)

    Your problem is that "Student (male): John" starts with an uppercase S, and you're trying to match a lowercase s. That's as simple as it gets!

    Note that you may use [()] to match either ( or ):

    p = p.replaceAll("[()]", "\\\\$0");
    

    By the way, I would also point out that you could replace the lines:

    p = p.replaceAll("\\(", "\\\\(");
    p = p.replaceAll("\\)", "\\\\)");
    

    Simply by using:

    p = Pattern.quote(p);
    

    Cheers!

    0 讨论(0)
  • 2021-01-24 18:55

    Because in line String text = "Student (male): John"; does not match with regex student \(male\)\:\s\w+

    Replace input text with text = "student (male): John"; or first phrase strings to phrases[0] = "Student (male)";

    Example on Ideone

    0 讨论(0)
  • 2021-01-24 18:58

    The following is not doing what you want:

     p = p.replaceAll("\\(", "\\\\(");
    

    You are replacing ( with \\\\(. \\\\( compiled in regex is \\(, which basicly means escape the \ and then (, not escape the (. What you are looking for is the following:

     p = p.replaceAll("\\(", "\\(");
    
    0 讨论(0)
提交回复
热议问题