r1chardj0n3s / parse

Parse strings using a specification based on the Python format() syntax.
http://pypi.python.org/pypi/parse
MIT License
1.72k stars 101 forks source link

How do I match in the middle of a string? #183

Closed Znunu closed 5 months ago

Znunu commented 5 months ago

Say I have one of two possible strings

I want to get "five birds", I've tried the following:

this fails with the second example:

parse("there are {} inside", my_string)

this fails with the first example:

parse("{}there are {} inside", my_string)

this doesn't work as there's a space between "five" and "birds":

search("there are {:l} inside", my_string)
wimglenn commented 5 months ago
>>> my_string1 = "there are five birds inside"
>>> my_string2 = "randomstring there are five birds inside"
>>> search("there are {} inside", my_string1)
<Result ('five birds',) {}>
>>> search("there are {} inside", my_string2)
<Result ('five birds',) {}>
Znunu commented 5 months ago

I think I understand now, thank you

jenisys commented 5 months ago

@Znunu ANSWER: For your question to parse something in the middle (independent of prefix)

# -- EXAMPLE: Parse something in the middle (independent of prefix)
import parse

@parse.with_pattern(r".*")
def parse_any_text(text):
    return text 

schema = "{:AnyText}there are {} inside"
text = "xxx there are 5 birds inside"
parse.parse(schema, text, extra_types=dict(AnyText=parse_any_text))
# -- RETURNS: <Result ('xxx ', '5 birds') {}>