【问题标题】:regex to match a single quote string that could contain ''' '' '''正则表达式匹配可能包含 ''' '' ''' 的单引号字符串
【发布时间】:2019-05-23 09:20:58
【问题描述】:

输入字符串可以是:

- "his 'pet''s name is tom' and she is 2 years old"
- " '''' "
- " '' "
- "function('name', test, 'age')"

我想从这些输入中获取单引号字符串,其中甚至可能在单引号字符串中包含''

我尝试否定前瞻(?!') 在匹配时忽略''

 '.*?'(?!')    

我期望输出

- 'pet''s name is tom'
- ''''
- 'name' and 'age'

【问题讨论】:

  • 我们想要pets name is tom 还是pet''s name is tom
  • pets''s name is tom
  • 是因为引号之间是空的吗?因为否则- "function('name', test, 'age')" 这将是name', test, 'age
  • 非空。它类似于转义字符 ` '' ` 表示字符串中的 ` ' `

标签: python regex


【解决方案1】:

我认为您可以通过

r"'[^']*(?:''[^']*)*'"

regex demo

说明

  • ' - 单引号
  • [^']* - 0+ 单引号以外的字符
  • (?:''[^']*)* - 零次或多次重复
    • '' - 两个单引号
    • [^']* - 0+ 单引号以外的字符
  • ' - 单引号

Regex graph:

【讨论】:

  • @ArunKumar 很高兴它对你有用。如果对您有用,也请考虑upvoting the answer
【解决方案2】:

r"'(.+?)'"获取单引号字符串

import re 

tx = "his 'pet''s name is tom' and she is 2 years old"

print(re.findall(r"\'(.+?)\'",tx)) 
#output :  ['pet', 's name is tom'] 

【讨论】:

  • 我认为要满足请求,您应该在正则表达式中将“+”替换为“*”,目前您得到两个匹配项,而您应该只得到一个匹配项
  • 同样的事情,只得到一个,删除这个? out this ["pet''s name is tom"]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 2022-06-21
相关资源
最近更新 更多