gpt4 book ai didi

python - 正则表达式 - 在符号后查找数字

转载 作者:行者123 更新时间:2023-12-05 07:08:07 26 4
gpt4 key购买 nike

我正在尝试使用下面的正则表达式来查找“|”之后的任何数字运算符来处理下面的几个示例字符串。问题在于默认的正则表达式,我似乎无法将 numerical_regex 与 Lookbehind 结合起来。

'xxx -> 31223.1 | xxx -> 1.1'.    to get 1.1

'0 | 1' to get 1

numeric_regex = '''
[-+]? # pos or neg
(?: (?: \d* \. \d+ ) | # float (ie .1 and 1.1)
(?: \d+ \.? ) ) # int (with trailing periods ie 1.)
'''

default_regex = f'''
(? <= \|). # after but not including |
{numeric_regex} # all digits
+ $ # end of the string
'''

感谢任何帮助!

最佳答案

以下是您的问题陈述的小程序

import re

regex = r"\|.*?[\-\+]?(\d+\.\d+|\d+\.?|\.\d+)"

test_str = ("xxx -> 31223.1 | xxx -> 1.1\n"
"0|1\n"
"0|abc 1.\n"
"0|.1\n")

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

你正在寻找的正则表达式是

regex = r"\|.*?[-+]?(\d+.\d+|\d+.?|.\d+)"

只测试了几个场景,希望对你有帮助。

关于python - 正则表达式 - 在符号后查找数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61937251/

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