Python正则表达式在字符串中查找双引号中的字符串 [英] Python Regex to find a string in double quotes within a string

查看:243
本文介绍了Python正则表达式在字符串中查找双引号中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中使用正则表达式的代码,可以执行类似的操作

A code in python using regex that can perform something like this

Input: Regex should return "String 1" or "String 2" or "String3" 
Output: String 1,String2,String3

谢谢

推荐答案

您只需:

def doit(text):      
  import re
  matches=re.findall(r'\"(.+?)\"',text)
  # matches is now ['String 1', 'String 2', 'String3']
  return ",".join(matches)

doit('Regex should return "String 1" or "String 2" or "String3" ')
# result:
'String 1,String 2,String3'

正如 Li-aung Yip 指出的:(我差点引用)

As pointed out by Li-aung Yip: (I nearly quote)

.+?.+ 的非贪婪"版本.它使正则表达式匹配它所能匹配的最少字符数而不是它所能匹配的最多字符数.贪婪的版本,.+,将给出字符串 1" or "String 2" or "String 3;非贪婪版本 .+? 'String 1,String 2,String3'

.+? is the "non-greedy" version of .+. It makes the regular expression match the smallest number of characters it can instead of the most characters it can. The greedy version, .+, will give string 1" or "String 2" or "String 3; the non-greedy version .+? 'String 1,String 2,String3'

另外(Johan 再说一遍),如果要接受空字符串,请将 .+ 更改为 .*.星号表示零个或多个 - 加号表示至少一个.

In addition (Johan speaking again), if you want to accept empty strings, change .+ to .*. Star means zero or more - plus means at least one.

这篇关于Python正则表达式在字符串中查找双引号中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆