python - 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.
解决方案
您可以使用以下解决方案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 -.
推荐阅读
- java - 不知道如何设置属性值(Java DOM Parser)
- typescript - 带有嵌套对象的 Object.keys():获取正确的类型
- sql - 使用 EXEC 的结果创建新表
- node.js - 如何使用 `ng new` 创建新应用程序?
- java - 如何在首选项中保存文件?
- c# - 如何使用 Sharppcap 获取 http 内容
- angular - 如何在 Ionic Angular 中播放音频?
- javascript - 您如何使用 Neptune 在本地进行测试?
- javascript - Javascript 中数组与对象的实例化。数组什么时候是对象,什么时候得到数组的方法?
- c++ - Mutex 不是 cv 的成员,用 g++ 编译失败