简体   繁体   English

正则表达式匹配“ \\\\ r”

[英]Regular Expression to match “\\r”

I'm having trouble writing a regex that matches these inputs: 我在编写与这些输入匹配的正则表达式时遇到了麻烦:
1. \\\\r 1. \\\\r
2. \\\\rSomeString 2. \\\\rSomeString
I need a regex that matches \\\\r 我需要一个匹配\\\\r的正则表达式

Escape the back slashes twice. 退回两次斜线。 String's interpret \\ as a special character marker. 字符串的解释\\为特殊字符标记。

Use \\\\\\\\r instead. 请改用\\\\\\\\r \\\\ is actually interpreted as just \\ . \\\\实际上被解释为\\

EDIT: So as per the comments you want any string that starts with \\\\r with any string after it. 编辑:因此,根据注释,您希望以\\\\r开头的任何字符串以及其后的任何字符串。 The regex pattern is as follows: 正则表达式模式如下:

(\\\\r\S*)

\\\\\\\\r is the string you want at the start and \\S* says any non-white space ( \\S ) can come after any number of times ( * ). \\\\\\\\r是您想在开始时输入的字符串, \\S*表示在任意次数( * )之后可以出现任何非空白( \\S )。

A literal backslash in Python can be matched with r'\\\\' (note the use of the raw string literal!). Python中的文字反斜杠可以与r'\\\\'相匹配(请注意使用原始字符串文字!)。 You have two literal backslashes, thus, you need 4 backslashes (in a raw string literal) before r . 您有两个文字反斜杠,因此,在r之前需要4个反斜杠(在原始字符串文字中)。

Since you may have any characters after \\\\r , you may use 由于\\\\r之后可能包含任何字符,因此可以使用

import re
p = re.compile(r'\\\\r\S*')
test_str = r"\\r \\rtest"
print(p.findall(test_str))

See Python demo 参见Python演示

Pattern description : 模式说明

  • \\\\\\\\ - 2 backslashes \\\\\\\\ -2个反斜杠
  • r - a literal r r文字r
  • \\S* - zero or more non-whitespace characters. \\S* -零个或多个非空白字符。

Variations : 变化

  • If the characters after r can only be alphanumerics or underscore, use \\w* instead of \\S* 如果r之后的字符只能是字母数字或下划线,请使用\\w*而不是\\S*
  • If you want to only match \\\\r before non-word chars, add a \\B non-word boundary before the backslashes in the pattern. 如果只想在非单词字符前匹配\\\\r ,请在模式中的反斜杠之前添加\\B非单词边界。

您可以在线(例如在此站点)微调正则表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM