gpt4 book ai didi

Python正则表达式在字符串中的双引号中查找字符串

转载 作者:IT老高 更新时间:2023-10-28 21:06:58 24 4
gpt4 key购买 nike

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

输入:Regex 应该返回“String 1”或“String 2”或“String3”

输出:String 1,String2,String3

我试过 r'"*"'

最佳答案

这就是你需要做的所有事情:

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" ')

结果:

'String 1,String 2,String3'

正如 Li-aung Yip 所指出的那样:

To elaborate, .+? 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 .+? gives String 1, String 2, String 3.

另外,如果要接受空字符串,请将.+ 改为.*。星号 * 表示零个或多个,加号 + 表示至少一个。

关于Python正则表达式在字符串中的双引号中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9519734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com