Check if string contains single backslashes with regex

前端 未结 3 2093
半阙折子戏
半阙折子戏 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:26

    It seems you just want to check if a string matches a regex pattern partially, namely, if it contains a literal backslash not preceded nor followed with a backslash.

    Use

    (?

    See the regex demo.

    Sample Scala code:

    val s = """"\This string\\ \contains some\ backslashes\""""
    val rx = """(? true
      case _ => false
    }
    println(ismatch)
    

    See the Scala online demo.

    Note:

    • """(? - this line declares a regex object and makes the pattern unanchored, so that no full string match is no longer required by the match block
    • Inside match, we use case rx(_*) as there is no capturing group defined inside the pattern itself
    • The pattern means: match a backslash (\\) that is not preceded with a backslash ((?) and is not followed with a backslash ((?!\\)).

提交回复
热议问题