Python中给定字符串中换行符搜索的正则表达式
我想在python中使用正则表达式搜索字符串中的换行符。我不想在消息中包含\r或\n 我已尝试使用能够正确检测\r\n的正则表达式。但是当我从行变量中删除\r\n时。它仍然会打印错误Python中给定字符串中换行符搜索的正则表达式,python,Python,我想在python中使用正则表达式搜索字符串中的换行符。我不想在消息中包含\r或\n 我已尝试使用能够正确检测\r\n的正则表达式。但是当我从行变量中删除\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"); 它应该检测\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");
它应该检测\r\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变量命名为 您正在寻找该函数
尝试这样做:
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");
正如其他人所指出的,您可能正在查找
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');
首先考虑使用带钢作为这里提到的许多人。 其次,如果您想匹配字符串中任何位置的换行符,请使用
search
notmatch
使用
Line.strip()
。将“得到的字节数少于请求的字节数”
作为输出。不需要使用正则表达式。不,使用line.rstrip()
删除右边的空格,而不是左边的空格。您希望实现什么?检测行尾还是删除行尾?对正则表达式使用原始字符串是有意义的,这样您就不需要转义转义字符r'\r | \n'
不需要对\r或\n使用原始字符串。它可以不使用,因为在很多情况下都是错误的,首先要匹配regexp中字符串的开头和结尾,需要使用特殊字符-^和$。第二,如果您想检查数据库中的任何位置,您应该使用search
notmatch
string@maxwell现在我按照你的方式做了,你高兴吗?你重新定义了相同的prog
变量→ 它将只匹配第二个regexpYep。它们是带有注释的示例,解释了每种方法的作用。应根据需要选择一个。对于问题作者,只有第二个问题适用,并且您正在使用regepx组()
,在这种情况下不需要这些组,它将执行操作,但问题作者希望实现检查(不执行任何操作);建议使用不同的方法是好的,但只能作为你答案的补充。否则你实际上没有回答这个问题
newline_regexp = re.compile("\n|\r")
newline_regexp.search(Line) # will give u search object or None if not found