Check if string contains single backslashes with regex

前端 未结 3 2047
半阙折子戏
半阙折子戏 2021-01-26 19:00

I have tried to fix this for a long time, and i just can\'t do it.

It could be any string, but this is an example:

\"\\This string \\contains some\\ bac         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-26 19:11

    Not sure what you're asking.. are you asking how to write a String literal that represents the String you gave as an example? You could either escape the backslash with another backslash, or use triple quotes.

    scala> "\\This string \\contains some\\ backslashes\\"
    String = \This string \contains some\ backslashes\
    
    scala> """\This string \contains some\ backslashes\"""
    String = \This string \contains some\ backslashes\
    

    And replace the backslashes using the same techniques.

    scala> "\\This string \\contains some\\ backslashes\\".replace("\\","\\\\")
    String = \\This string \\contains some\\ backslashes\\
    

    or

    scala> """\This string \contains some\ backslashes\""".replace("""\""","""\\""")
    String = \\This string \\contains some\\ backslashes\\
    

    But I have a feeling you want to do something else, like validate input. Maybe you could provide a bit more context?

提交回复
热议问题