正则表达式:如何从字符串中去除 's?

3

字符串输入:Python的编程:非常容易学习

期望输出:Python编程:非常容易学习

这是目前我所做的,但并不起作用:

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

我该如何从Python中去除's?


请参阅 https://dev59.com/m3NA5IYBdhLWcg3wpvtg#875978 - tripleee
这个回答解决了你的问题吗?从Python字符串中删除特定字符 - jalazbe
1
从Python中的字符串中删除特定字符与当前问题无关。 - Wiktor Stribiżew
2个回答

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代码

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

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

在不检查单词边界的情况下替换 's 可能会导致副作用。尝试使用 'such an awesome language' 字符串。 - Ryszard Czech
我其实不确定你说的是不是真的。在你的字符串中没有单词边界似乎也能正常工作。除非你指的是mystr = "'such an awesome language'"。但这似乎极不可能。 - noah
我已经去掉了单词边界。我认为在这种情况下它们是不必要的。 - noah
并且并不打算“抄袭”你的答案。我只是看到了对我的回答的评论,并进行了回应。之前并没有看过你的答案。 - noah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接