[英]Python regex for matching odd number of consecutive backslashes
I want to find all odd number of continuous backslashes. 我想找到所有奇数连续的反斜杠。
I tried the following expression: 我尝试了以下表达式:
(?<!\\)(\\)(?!\\)
However, it matches a single backslash if present. 但是,它匹配单个反斜杠(如果存在)。
You can try this too: 你也可以试试这个:
(?<!\\)(?:\\{2})*\\(?!\\)
(?<!\\\\)
No backslash in the back from the current location (?<!\\\\)
当前位置后面没有反斜杠 (?:\\\\{2})
matches each next consecutive pairs of backslash , zero or more occasion (?:\\\\{2})
匹配每个下一对连续的反斜杠,零或多个场合 \\\\
matches a single backslash \\\\
匹配单个反斜杠 (?!\\\\)
then checks if there is no more backslash immediately (?!\\\\)
然后检查是否没有立即反斜杠 You may use 你可以用
r'(?<!\\)\\(?:\\{2})*(?!\\)'
See the regex demo . 请参阅正则表达式演示 。
Details : 细节 :
(?<!\\\\)
- no backslash can appear right before the current location (?<!\\\\)
- 在当前位置之前不会出现反斜杠 \\\\
- a single backslash \\\\
- 一个反斜杠 (?:\\\\{2})*
- 0 or more occurrences of 2 backslashes (?:\\\\{2})*
- 0次或更多次出现2个反斜杠 (?!\\\\)
- no \\
can appear immediately to the right at the current location. (?!\\\\)
- 没有\\
可以立即出现在当前位置的右侧。 Note that in Python it is a good idea to use raw string literal when using literal backslashes in a regex pattern (to reduce the number of escapes and make the pattern look tidier, and avoid any issues related to misinterpreted backslashes.) 请注意,在Python中,在正则表达式模式中使用文字反斜杠时使用原始字符串文字是个好主意(减少转义次数并使模式看起来更整洁,并避免与错误解释的反斜杠相关的任何问题。)
If you're looking for speed, this benchmarks the best: 如果您正在寻找速度,那么这个最佳基准:
\\\\(?<!\\\\\\\\)(?:\\\\\\\\)*(?!\\\\)
Regex1: \\(?<!\\\\)(?:\\\\)*(?!\\)
Options: < none >
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 3
Elapsed Time: 0.23 s, 229.23 ms, 229231 µs
Regex2: (?<!\\)\\(?:\\{2})*(?!\\)
Options: < none >
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 3
Elapsed Time: 0.83 s, 829.68 ms, 829684 µs
Regex3: (?<!\\)(?:\\{2})*\\(?!\\)
Options: < none >
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 3
Elapsed Time: 1.09 s, 1086.34 ms, 1086340 µs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.