Skip to main content
 首页 » 编程设计

Python之使用冗长的正则表达式解析用户输入

2025年05月04日25artech

我正在尝试设计一个正则表达式,它将以完整句子的形式解析用户输入。我正在努力让我的表情充分发挥作用。我知道它编码不好,但我正在努力学习。我目前正试图让它解析 precent 作为代码下看到的一个字符串。

My test "sentence"= How I'm 15.5% wholesome-looking U.S.A. we RADAR () [] {} you -- are, ... you?

text = input("please type somewhat coherently: ") 
 
pattern = r'''(?x)              # set flag to allow verbose regexps 
    (?:[A-Z]\.)+                # abbreviations, e.g. U.S.A. 
    |\w+(?:[-']\w+)*            # permit word-internal hyphens and apostrophes 
    |[-.(]+                     # double hyphen, ellipsis, and open parenthesis 
    |\S\w*                       # any sequence of word characters 
    # |[\d+(\.\d+)?%]           # percentages, 82% 
    |[][\{\}.,;"'?():-_`]       # these are separate tokens 
    ''' 
 
parsed = re.findall(pattern, text) 
print(parsed) 

我的输出 = ['How', "I'm", '15', '.', '5', '%', 'wholesome-looking', 'U.S.A.', 'we', 'RADAR', '(', ')', '[', ']', '{', '}', '你', '--', '是', ',', '...' , '你', '?']

我希望将 '15'、'.'、'5'、'%' 解析为 '15.5%'。当前被注释掉的行是应该做的,但是当被注释掉时绝对什么都不做。我搜索了可提供帮助的资源,但没有找到。

感谢您的宝贵时间。

请您参考如下方法:

如果您只想将百分比匹配作为一个整体实体,您真的应该知道正则表达式引擎会从左到右分析输入字符串和模式。如果您有一个替代方案,将选择与输入字符串匹配的最左边的替代方案,其余的甚至不会被测试。

因此,您需要拉取替代项 \d+(?:\.\d+)?向上,捕获组应该变成非捕获或 findall会产生奇怪的结果:

(?x)              # set flag to allow verbose regexps 
(?:[A-Z]\.)+                # abbreviations, e.g. U.S.A. 
|\d+(?:\.\d+)?%           # percentages, 82%  <-- PULLED UP OVER HERE 
|\w+(?:[-']\w+)*            # permit word-internal hyphens and apostrophes 
|[-.(]+                     # double hyphen, ellipsis, and open parenthesis 
|\S\w*                       # any sequence of word characters# 
|[][{}.,;"'?():_`-]       # these are separate tokens 

参见 regex demo .

另外,请注意我替换了[][\{\}.,;"'?():-_`]与 [][{}.,;"'?():_`-] : 大括号不必转义,-正在从匹配 ; 的冒号(十进制代码 58)和下划线(十进制 95)形成不必要的范围, < , = , > , ? , @ , 所有大写拉丁字母, [ , \ , ]和 ^ .