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
286 views
in Technique[技术] by (71.8m points)

c# - Regex to return the word before the match

I've been trying to extract the word before the match. For example, I have the following sentence:

"Allatoona was a town located in extreme southeastern Bartow County, Georgia."

I want to extract the word before "Bartow".

I've tried the following regex to extract that word:

wsCounty,

What I get returned is "w County" when what I wanted is just the word Bartow.

Any assistance would be greatly appreciated. Thanks!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use this regex with a lookahead to find word before County:

w+(?=s+County)

(?=s+County) is a positive lookahead that asserts presence of 1 or more whitespaces followed by word County ahead of current match.

RegEx Demo

If you want to avoid lookahead then you can use a capture group:

(w+)s+County

and extract captured group #1 from match result.


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

...