Check if string contains single backslashes with regex

纵饮孤独 提交于 2020-01-22 01:48:27

问题


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\ backslashes\"

I need to make a regex that i can use to check that the string contains single backslashes.

I then need to convert the given string into (i can do the conversion):

"\\This string \\contains some\\ backslashes\\"

And then use regex to check that the string no long contains single backslashes.

Btw i dont have to use regex for this, i just need to be able to check the strings somehow.


回答1:


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 = """(?<!\\)\\(?!\\)""".r.unanchored
val ismatch = s match {
  case rx(_*) => true
  case _ => false
}
println(ismatch)

See the Scala online demo.

Note:

  • """(?<!\\)\\(?!\\)""".r.unanchored - 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 ((?!\\)).



回答2:


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?




回答3:


Try This

val s = """\This string \contains some\ backslashes\"""

s.replaceAll("""\\""","""\\\\""")


来源:https://stackoverflow.com/questions/42019167/check-if-string-contains-single-backslashes-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!