正则表达式:从字符串中删除?

时间:2020-10-01 21:04:30

标签: python regex

字符串输入:readline

预期输出:stream.on

这是我到目前为止无法使用的内容:

Python's Programming: is very easy to learn

如何从Python Programming: is very easy to learn中删除import re mystr = "Python's Programming: is very easy to learn" reg = r'\w+' print(re.findall(reg, mystr))

2 个答案:

答案 0 :(得分:2)

您提取一个或多个字母数字字符的所有匹配项。

使用

\b's\b

请参见proof

说明

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  's                       '\'s'
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

Python code

import re
mystr = "Python's Programming: is very easy to learn"
print(re.sub(r"\b's\b", '', mystr))

答案 1 :(得分:0)

这里有两个选择。第一个使用正则表达式,第二个使用字符串replace方法。

import re
mystr = "Python's Programming: is very easy to learn"
reg = r"'s"
print(re.sub(reg, '', mystr))
   # prints: Python Programming: is very easy to learn
print(mystr.replace("'s",''))
   # prints: Python Programming: is very easy to learn