Skip to main content
 首页 » 编程设计

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

2024年10月01日32mate10pro

我的目标是从 Lorem 'hello_kitty.dat' ipsum. 中选择像 hello_kitty.dat 这样的字符串。

我写的这个片段在一定程度上适用于较小的字符串 (从teststring中选择一个或多个(+)单词字符(\w)在点(\.)之前) 后面有三个单词字符 (\w{3}) 并用 xsubstitute 选择)。

>>> 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 因为它在单行之外引号。

请您参考如下方法:

您可以使用:

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+ 个字符匹配的否定字符类
  • ' - 单引号。