Java Regex Escape Characters

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

    \ is special character in String literals "...". It is used to escape other special characters, or to create characters like \n \r \t.
    To create \ character in string literal which can be used in regex engine you need to escape it by adding another \ before it (just like you do in regex when you need to escape its metacharacters like dot \.). So String representing \ will look like "\\".

    This problem doesn't exist when you are reading data from user, because you are already reading literals, so even if user will write in console \n it will be interpreted as two characters \ and n.


    Also there is no point in adding | inside class character [...] unless your intention is to make that class also match | character, remember that [abc] is the same as (a|b|c) so there is no need for | in "[\\d|\\s]".

提交回复
热议问题