Java Regex Escape Characters

后端 未结 4 980
被撕碎了的回忆
被撕碎了的回忆 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:29

    If you want to represent a backslash in a Java string literal you need to escape it with another backslash, so the string literal "\\s" is two characters, \ and s. This means that to represent the regular expression [\d\s][\d]\. in a Java string literal you would use "[\\d\\s][\\d]\\.".

    Note that I also made a slight modification to your regular expression, [\d|\s] will match a digit, whitespace, or the literal | character. You just want [\d\s]. A character class already means "match one of these", since you don't need the | for alternation within a character class it loses its special meaning.

提交回复
热议问题