Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何匹配和替换特定字符之前或之后的任何内容?_Python_Regex - Fatal编程技术网

在Python中,如何匹配和替换特定字符之前或之后的任何内容?

在Python中,如何匹配和替换特定字符之前或之后的任何内容?,python,regex,Python,Regex,我试图理解特定字符前后的匹配模式 我有一个字符串: myString = "A string with a - and another -." 问题:在下面的替换函数中应该使用什么正则表达式,它允许我匹配第一个“-”字符之后的任何内容,以便下面的函数打印它之前的所有内容 print re.sub(r'TBD', '', myString) # would yield "A string with a " 问题如果我想匹配第一个'-'字符之前的所有内容,它会发生什么变化 print re.su

我试图理解特定字符前后的匹配模式

我有一个字符串:

myString = "A string with a - and another -."
问题:在下面的替换函数中应该使用什么正则表达式,它允许我匹配第一个“-”字符之后的任何内容,以便下面的函数打印它之前的所有内容

print re.sub(r'TBD', '', myString) # would yield "A string with a "
问题如果我想匹配第一个'-'字符之前的所有内容,它会发生什么变化

print re.sub(r'TBD', '', myString) # would yield " and another -."

提前感谢您提供的任何帮助。

使用带有“向前看”和“向后看”的“重新搜索”来匹配第一次出现的情况:

import re

myString = "A string with a - and another -."

print(re.search(r'.*?(?=-)', myString).group())  # A string with a

print(re.search(r'(?<=-).*', myString).group())  # and another -.

re.search将为您提供答案,您可以通过将其转换为列表并重新加入来编辑答案

import re

m = re.compile(r'(.*?)[-]')
p = m.search('A string with a - and another -.')
print(''.join(list(p.group())[:-1]))

n = re.compile(r'-(.*?)-')
q = n.search('A string with a - and another -.')
print(''.join(list(q.group())[1:]))

对于
re.sub
,您可以使用以下解决方案:

import re

myString = "A string with a - and another -."
print(re.sub(r'-.*',r'',myString))
#A string with a 
print(re.sub(r'^[^-]+-',r'',myString))
# and another -.
str.partition()

my_string = "A string with a - and another -."
s = my_string.partition('-')
print(s[0]) # A string with a 
print(s[-1]) # and another -.
my_string = "A string with a - and another -."
s = my_string.partition('-')
print(s[0]) # A string with a 
print(s[-1]) # and another -.