简体   繁体   English

Python解析空字符串

[英]Python parse empty string

I'm using the parse library and ran into surprising (to me) functionality: it does not match empty strings: 我正在使用parse库,遇到了令我惊讶的功能:它不匹配空字符串:

>>> from parse import parse
>>> parse('hi "{}"', 'hi "everybody"')
<Result ('everybody',) {}>
>>> parse('hi "{}"', 'hi ""')
>>> 

Is there a way, using parse , to get it to match any string between "" in the same way that re does: 有没有一种方法,可以使用parse ,以使其与""之间的任何字符串匹配,方法与re相同:

>>> from re import match
>>> match('hi "(.*)"', 'hi "everybody"').groups()
('everybody',)
>>> match('hi "(.*)"', 'hi ""').groups()
('',)

Use a custom type conversion: 使用自定义类型转换:

from parse import parse
def zero_or_more_string(text):
    return text

zero_or_more_string.pattern = r".*"
parse('hi "{:z}"', 'hi ""', { "z": zero_or_more_string })

and you'll get this: 然后您会得到:

<Result ('',) {}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM