gpt4 book ai didi

Python/正则表达式 : Get all strings between any two characters

转载 作者:行者123 更新时间:2023-12-01 02:09:12 25 4
gpt4 key购买 nike

我有一个用例,需要识别任意两个字符之间的许多不同文本片段。

例如,

  1. 单个空格和 ( 之间的字符串:def test()会回来 test
  2. 单词和空格 ( paste ) 和特殊字符 ( / ) 之间的字符串: @paste "game_01/01"将返回"game_01
  3. 单个空格和 ( 之间的字符串具有多个目标字符串:} def test2() { Hello(x, 1)将返回test2Hello

为此,我尝试编写一些通用的内容来识别任意两个字符之间的最短字符串。

我目前的方法是(来自chrisz):

pattern = '{0}(.*?){1}'.format(re.escape(separator_1), re.escape(separator_2))

对于第一个用例,separator_1 = \sseparator_2 = ( 。这不起作用,所以显然我错过了一些东西,但不确定是什么。

tl;dr 如何编写通用正则表达式来解析任意两个字符之间的最短字符串?

  • 注意:我知道有很多这样的例子,但它们看起来非常具体,如果可能的话,我正在寻找通用的解决方案。

最佳答案

请告诉我这是否是您正在寻找的内容:

import re

def smallest_between_two(a, b, text):
return min(re.findall(re.escape(a)+"(.*?)"+re.escape(b),text), key=len)

print(smallest_between_two(' ', '(', 'def test()'))
print(smallest_between_two('[', ']', '[this one][not this one]'))
print(smallest_between_two('paste ', '/', '@paste "game_01/01"'))

输出:

test
this one
"game_01

添加对其作用的解释:

re.findall() :

Return all non-overlapping matches of pattern in string, as a list of strings

re.escape()

Escape all the characters in pattern except ASCII letters and numbers. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it

(.*?)

.*? matches any character (except for line terminators)

*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)

因此我们的正则表达式匹配两个任意转义字符串之间的任何字符(不包括行终止符),然后返回 list 中最短长度的字符串。那re.findall()返回。

关于Python/正则表达式 : Get all strings between any two characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819569/

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