使用正则表达式检查字符串是否包含单个反斜杠 [英] Check if string contains single backslashes with regex
问题描述
我已经尝试解决这个问题很长时间了,但我就是做不到.
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.
推荐答案
您似乎只想检查字符串是否部分匹配正则表达式模式,即,它是否包含前面或后面没有反斜杠的文字反斜杠.
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.
使用
(?<!\\)\\(?!\\)
查看正则表达式演示.
Scala 代码示例:
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)
查看 Scala 在线演示.
注意:
"""(?<!\\)\\(?!\\)""".r.unchored
- 这一行声明了一个正则表达式对象并使模式非锚定,所以match
块 不再需要完整的字符串匹配- 在
match
中,我们使用case rx(_*)
,因为在模式本身内部没有定义捕获组 - 该模式表示:匹配前面没有反斜杠 (
(?<!\\)
) 并且后面没有跟的反斜杠 (\\
)反斜杠 ((?!\\)
).
"""(?<!\\)\\(?!\\)""".r.unanchored
- this line declares a regex object and makes the pattern unanchored, so that no full string match is no longer required by thematch
block- Inside
match
, we usecase 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 ((?!\\)
).
这篇关于使用正则表达式检查字符串是否包含单个反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!