python - 正则表达式 - 选择单引号之间的表达式

标签 python regex

我的目标是从 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/

相关文章:

python - 当将 text() 与 python-escpos 一起使用时,我得到 [Errno None] 和关键错误 = 1 (windows 10)

python - Python 的 VS Code 函数签名 IntelliSense 从哪里来?

python - 错误 : "Driver not loaded" in PyQt5

mysql - 如果包含特定字符,如何重命名WordPress帖子标题

java - 正则表达式检查不包含\> <的字符串检查

python - 通过移动应用程序在 Raspberry Pi 上切换显示 OSMC 的电视

java - 使用括号拆分

regex - 使用 awk 只包含以特定值开头的列?

javascript - 正则表达式与我的示例不匹配

python - 转换为大写。哪种方式更pythonic?