繁体   English   中英

正则表达式在Python中给定字符串中的换行符搜索

[英]Regex for newline character search in given string in Python

我想在python中使用正则表达式搜索字符串中的换行符,我不想在Message中包含\\ r或\\ n。

我已经尝试过能够正确检测\\ r \\ n的正则表达式。 但是当我从Line变量中删除\\ r \\ n时。 仍然会打印错误。

Line="got less no of bytes than requested\r\n"

if(re.search('\\r|\\n',Line)):
      print("Do not use \\r\\n in MSG");

它应该在Line变量中检测\\ r \\ n,该变量作为文本而不是不可见的\\ n。

当行如下所示时,它不应打印:

Line="got less no of bytes than requested"

与其检查换行符,不如删除它们可能更好。 无需使用正则表达式,只需使用strip ,它将删除字符串末尾的所有空格和换行符:

line = 'got less no of bytes than requested\r\n'
line = line.strip()
# line = 'got less no of bytes than requested'

如果要使用正则表达式,可以使用:

import re

line = 'got less no of bytes than requested\r\n'
line = re.sub(r'\n|\r', '', line)
# line = 'got less no of bytes than requested'

如果您坚持检查换行符,则可以这样进行:

if '\n' in line or '\r' in line:
    print(r'Do not use \r\n in MSG');

或与正则表达式相同:

import re

if re.search(r'\n|\r', line):
    print(r'Do not use \r\n in MSG');

另外:建议您将Python变量命名为snake_case

您正在寻找re.sub函数。

尝试这样做:

Import re
Line="got less no of bytes than requested\r\n"
replaced = re.sub('\n','',Line)
replaced = re.sub('\r','',Line)
print replaced 

如果只想检查消息中的换行符,则可以使用字符串函数find() 注意使用原始文本,如字符串前面的r所示。 这消除了转义反斜杠的需要。

line = r"got less no of bytes than requested\r\n"
print(line)
if line.find(r'\r\n') > 0:
    print("Do not use line breaks in MSG");

首先,要像这里提到的许多人一样使用脱衣舞。

其次,如果要在字符串的ANY位置匹配换行符,请使用search not match

re.search和re.match有什么区别? 这是有关搜索与匹配的更多信息

newline_regexp = re.compile("\n|\r")
newline_regexp.search(Line)  # will give u search object or None if not found

正如其他人指出的那样,您可能正在寻找line.strip() 但是,如果您仍然想练习正则表达式,则可以使用以下代码:

Line="got less no of bytes than requested\r\n"

# \r\n located anywhere in the string
prog = re.compile(r'\r\n')
# \r or \n located anywhere in the string
prog = re.compile(r'(\r|\n)')


if prog.search(Line):
    print('Do not use \\r\\n in MSG');

暂无
暂无

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

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