首页 > 解决方案 > In Python, how do I match and substitute anything before or after a specific character?

问题描述

I'm trying to understand matching patterns before or after a specific character.

I have a string:

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

QUESTION: What regular expression should be used in the following substitution function that allows me to match anything after the first '-' character such that the following function would print everything before it?

print re.sub(r'TBD', '', myString) # would yield "A string with a "

QUESTION How would it change if I wanted to match everything before the first '-' character?

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

Thanks, in advance, for any help you can offer.

标签: pythonregex

解决方案


您可以使用以下解决方案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 -.

推荐阅读