我的目标是从 Lorem 'hello_kitty.dat' ipsum.
中选择像 hello_kitty.dat
这样的字符串。
我写了这个片段,在某种程度上适用于较小的字符串
(从 teststring
中选择一个或多个 (+
) 单词字符 (\w
) 之前的点 (\.
) ),其后添加三个单词字符 (\w{3}
),并用 x
替换选择内容。
>>> teststring = "Lorem 'hello_kitty.dat' ipsum."
>>> print(re.sub(r'\w+\.\w{3}', "x", teststring))
"Lorem 'x' ipsum."
但是,即使在 \w{3}
之后不完全遵循我的模式,我如何修改代码以选择单引号之间的所有内容?
teststring
可能是
"Lorem 'hello_kitty.cmd?command91' ipsum hello_kitty.cmd?command92"
但在这种情况下不想选择 hello_kitty.cmd?command92
因为它位于 single 之外报价。
最佳答案
您可以使用:
import re
teststring = "Lorem 'hello_kitty.cmd?command91' ipsum hello_kitty.cmd?command92"
print(re.sub(r"'\w+\.\w{3}[^']*'", "'x'", teststring))
# => Lorem 'x' ipsum hello_kitty.cmd?command92
请参阅Python demo
模式现在匹配:
'
- 单引号\w+
- 1 个或多个单词字符\.
- 一个点\w{3}
- 3 个单词字符[^']*
- 否定字符类,匹配除单引号之外的任意 0 个以上字符'
- 单引号。
关于python - 正则表达式 - 选择单引号之间的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43506147/