【问题标题】:Python Regex replace all newline characters directly followed by a char with charPython Regex 用 char 替换所有直接后跟 char 的换行符
【发布时间】:2019-09-08 07:15:49
【问题描述】:
示例字符串:
str = "test sdf sfwe \n \na dssdf
我想替换:
\na
与
a
“a”可以是任何字符。
我试过了:
str = "test \n \na"
res = re.sub('[\n.]','a',str)
但是我如何存储\n 后面的字符并将其用作替换?
【问题讨论】:
标签:
python
regex
replace
newline
【解决方案1】:
您可以将此正则表达式与捕获组一起使用:
>>> s = "test sdf sfwe \n \na dssdf"
>>> >>> print re.sub(r'\n(.)', r'\1', s)
test sdf sfwe a dssdf
搜索正则表达式r'\n(.)' 将匹配\n 后跟任何字符并捕获组#1 中的后续字符
替换r'\1' 是对被放回原始字符串中的捕获组#1 的反向引用。
最好避免将str 作为变量名,因为它是python 中的保留关键字(函数)。
如果任何字符是指任何非空格字符,则使用此正则表达式并使用\S(非空白字符)而不是.:
>>> print re.sub(r'\n(\S)', r'\1', s)
test sdf sfwe
a dssdf
此外,这种基于前瞻的方法也可以在不需要任何捕获组的情况下工作:
>>> print re.sub(r'\n(?=\S)', '', s)
test sdf sfwe
a dssdf
请注意,[\n.] 将匹配 任何一个 \n 或文字点,而不是 \n 后跟任何字符,
【解决方案2】:
找到所有匹配项:
matches = re.findall( r'\n\w', str )
全部替换:
for m in matches :
str = str.replace( m, m[1] )
就是这样,伙计们! =)
【解决方案3】:
我认为最适合你的方法是让你的文本中没有更多空格:
string = "test sdf sfwe \n \na dssdf"
import re
' '.join(re.findall('\w+',string))
'test sdf sfwe a dssdf'