正则表达式在比赛前返回单词 [英] Regex to return the word before the match

查看:55
本文介绍了正则表达式在比赛前返回单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在比赛之前提取单词.例如,我有以下句子:

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

" Allatoona是位于佐治亚州巴托县东南部的一个小镇."

我想提取"Bartow"之前的词.

I want to extract the word before "Bartow".

我已经尝试过以下正则表达式来提取该单词:

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

\w\sCounty,

当我想要的只是Bartow一词时,我得到的是"w县".

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

任何帮助将不胜感激.谢谢!

Any assistance would be greatly appreciated. Thanks!

推荐答案

您可以在正则表达式中使用此正则表达式在 County 之前查找单词:

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

\w+(?=\s+County)

(?= \ s + County)是肯定的超前行为,它断言在当前匹配之前存在1个或多个空格,后跟单词 County .

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

RegEx演示

如果要避免超前,则可以使用捕获组:

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

(\w+)\s+County

并从匹配结果中提取捕获的#1组.

and extract captured group #1 from match result.

这篇关于正则表达式在比赛前返回单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆