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

时间:2019-03-28 13:09:05

标签: 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"

5 个答案:

答案 0 :(得分:0)

与其检查换行符,不如将它们删除可能会更好。无需使用正则表达式,只需使用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');

也:建议使用snake_case命名Python变量。

答案 1 :(得分:0)

您正在寻找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 

答案 2 :(得分:0)

如果只想检查消息中的换行符,则可以使用字符串函数import java.util.Random; public class Deck { // Declare the private attributes private static Random numberGenerator = new Random(123); // other attributes and methods follow } 。注意使用原始文本,如字符串前面的find()所示。这样就无需转义反斜杠。

r

答案 3 :(得分:0)

首先考虑使用这里提到的很多人。

第二,如果要在字符串的任意位置匹配换行符,请使用search而不是match

What is the difference between re.search and re.match? Here is more about search vs match

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

答案 4 :(得分:-1)

正如其他人所指出的,您可能正在寻找-S。但是,如果您仍然想练习正则表达式,则可以使用以下代码:

line.strip()