Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

parsing - Regex with negative lookahead across multiple lines

For the past few hours I've been trying to match address(es) from the following sample data and I can't get it to work:

medicalHistory      None
address             24 Lewin Street, KUBURA, 
                NSW, Australia
email               [email protected]


address             16 Yarra Street, 
                                     LAWRENCE, VIC, Australia
name                Mary   Beor
medicalHistory      None
phone               00000000000000000000353336907
birthday            26-11-1972

My plan was to find anything that starts with "address", is followed by any space followed by characters, numbers commas and newlines and ends with newline followed by a character. I came up with the following (and many variations of it):

addresss+([0-9a-zA-Z, 
]+)(?!
w)

Unfortunately that matches the following:

address             24 Lewin Street, KUBURA,
                NSW, Australia
email               MaryBeor  

and

address             16 Yarra Street,
                                 LAWRENCE, VIC, Australia
name                Mary   Beor
medicalHistory      None
phone               00000000000000000000353336907
birthday            26

instead of

address             24 Lewin Street, KUBURA, 
                NSW, Australia

and

address             16 Yarra Street,
                                 LAWRENCE, VIC, Australia

Can you please tell me what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would do it this way:

addresss+((?![
]+w)[0-9a-zA-Z, 
])+

See it here on Regexr.

This ((?![ ]+w)[0-9a-zA-Z, ])+ is the important part, where I say, match the next character from [0-9a-zA-Z, ], if (?![ ]+w) is not following. This is matching what you expect.

In both your cases the regex stopped matching because of a character that is not included in your character class. If you want to go that way than you would need to combine a lazy quantifier and a positive lookahead:

addresss+([0-9a-zA-Z, 

]+?)(?=
w)

[0-9a-zA-Z, ]+? is matching as less as possible till the condition (?= w) is true.

See it here at Regexr


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...