Java Regex Escape Characters

后端 未结 4 973
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 04:40

I\'m learning Regex, and running into trouble in the implementation.

I found the RegexTestHarness on the Java Tutorials, and running it, the following s

4条回答
  •  独厮守ぢ
    2020-12-07 05:39

    My pattern is any double digit or single digit preceded by a space, followed by a period.)

    Correct regex will be:

    Pattern pattern = Pattern.compile("(\\s\\d|\\d{2})\\.");
    

    Also if you're getting regex string from user input then your should call:

    Pattern.quote(useInputRegex);
    

    To escape all the regex special characters.

    Also you double escaping because 1 escape is handled by String class and 2nd one is passed on to regex engine.

提交回复
热议问题