我有很多像这样的字符串模式的例子,但我想展示一些例子。
from: [name: Illianney Amada
id: 674176087]
from: [name: Natalia Morel-Gibbs
id: 100003799207624]
from: [name: Jules Kaneyge Pand
id: 100000110811550]
而且,我想说明这样的参数类型:(观看字符串和 SequenceOfNumber )
from: [name: String
id: SequenceOfNumber]
但实际上,它是从这个
表示的from:\t[name:\tString\nid:\tSequenceofNumber]
所以,我想用替换“String”和“id:”之间的“\ n” >“,\ t”或制表符。结果应该是这样的
from:\t[name:\tString,\tid:\tSequenceofNumber]\n
from:\t[name:\tString,\tid:\tSequenceofNumber]\n
from:\t[name:\tString,\tid:\tSequenceofNumber]\n
或以其他方式这样
from: [name: String, id: SequenceOfNumber]
from: [name: String, id: SequenceOfNumber]
from: [name: String, id: SequenceOfNumber]
注意:我使用Python模块 re
实现正则表达式替换答案 0 :(得分:1)
<强>更新强>
import re
fixed = re.sub(r"(\[name:.*?)\n", r"\1,\t", originalString, re.M)
结果:
from: [name: Illianney Amada, id: 674176087]
from: [name: Natalia Morel-Gibbs, id: 100003799207624]
from: [name: Jules Kaneyge Pand, id: 100000110811550]
工作示例:http://regex101.com/r/wN7aT0
<强>旧强>
如果你只有那个\n
,你可以这样做:
originalString = "from:\t[name:\tString\nid:\tSequenceofNumber]"
fixedString = ",\t".join(originalString.split("\n"))
这会将\n
上的字符串拆分并与,\t
一起重新加入,从而产生:
from:\t[name:\tString,\tid:\tSequenceofNumber]
原始示例中的警告:,您实际上并未在变量中设置字符串。你是否可以从文本文件中打开它?如果是这样,那会大大改变答案,因为你可能一次循环一行。
答案 1 :(得分:0)
如果只替换模式中的'\ n',那么就像这样:
import re
data = """from: [name: Jules Kaneyge Pand
id: 100000110811550]
from: [name: abcd
id: 100000110811550]
"""
print ',\tid:'.join(re.split("[^\]]\s*\n\s*id:", data))
你会得到:
from: [name: Jules Kaneyge Pan, id: 100000110811550]
from: [name: abc, id: 100000110811550]