Python正则表达式从多个字符串中提取子字符串,包括\n
我想从给定的字符串中提取一个子字符串-Python正则表达式从多个字符串中提取子字符串,包括\n,python,regex,Python,Regex,我想从给定的字符串中提取一个子字符串- string0 = 'Daily wage of the worker0.1- \nNone' string1 = 'Daily wage of the worker0.2- \nInvalid' string3 = 'Daily wage of the worker0.3- \nValid' 有50个类似格式的字符串。我想从每行中提取-\n。什么是正确的正则表达式 我正在尝试re.search(r'^-\\n$',re.DOTALL)。我需要做哪些修改
string0 = 'Daily wage of the worker0.1- \nNone'
string1 = 'Daily wage of the worker0.2- \nInvalid'
string3 = 'Daily wage of the worker0.3- \nValid'
有50个类似格式的字符串。我想从每行中提取-\n
。什么是正确的正则表达式
我正在尝试
re.search(r'^-\\n$',re.DOTALL)
。我需要做哪些修改?您可以匹配您指定的模式:
import re
s = ['Daily wage of the worker0.1- \nNone', 'Daily wage of the worker0.2- \nInvalid', 'Daily wage of the worker0.3- \nValid']
new_s = [re.findall('- \n', i)[0] for i in s]
输出:
['- \n', '- \n', '- \n']
您可以匹配指定的模式:
import re
s = ['Daily wage of the worker0.1- \nNone', 'Daily wage of the worker0.2- \nInvalid', 'Daily wage of the worker0.3- \nValid']
new_s = [re.findall('- \n', i)[0] for i in s]
输出:
['- \n', '- \n', '- \n']
删除
^
,$
和re.DOTALL
我强烈建议在谷歌上搜索“在线正则表达式测试工具”,因为我发现它们在编写正则表达式之前对编写和测试正则表达式非常有价值。感谢您的帮助。它起作用了。和@SherylHohman谢谢你的建议,我会先用它们来测试我的表达式删除^
,$
和re.DOTALL
我强烈建议谷歌搜索“在线正则表达式测试工具”,因为我发现它们对于编写和测试正则表达式非常有用,然后再编写代码。谢谢你的帮助。它起作用了。还有@SherylHohman谢谢你的建议,我会先用它们来测试我的表情