使用正则表达式提取特定文本之前的数字 [英] Extracting number preceding a particular text using a regex

查看:1714
本文介绍了使用正则表达式提取特定文本之前的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个正则表达式从同一文本中提取两个数字(它们可以独立运行,无需一次提取两个数字.

我正在使用Yahoo管道.

原始文本:S $ 5,200/month可商议,1,475平方英尺/137平方米(内置)-公寓,10 Anson Road(D02)

需要提取为一个数字:1,475 并且(但可以在单独的实例上提取) 需要提取为数字:137

我在另一个论坛上从非常有帮助的人那里得到了以下模式:

\ b(\ d +(,\ d +)*)\ s +(sqft | sqm)

但是当我去替换$ 1并使用它时,它将带回整个源文本,而不仅仅是我想要的数字(即1,475或137,这取决于我是否运行) \ b(\ d +(,\ d +))\ s +(sqft)或\ b(\ d +(,\ d +))\ s +(sqm)

我在做什么错?

解决方案

好吧,您可以通过遍历比赛并以这种方式获得结果来做到这一点.

但是,如果您要使用replace方法,则可以使用该方法:

^.*?(?<sqft>\d+(,\d+)*)\s?sqft.*?(?<sqm>\d+(,\d+)*)\s?sqm.*$

然后替换为:

${sqft}
${sqm}

这里正在起作用.

无论sqft或sqm编号中是否包含逗号,都可以使用.并且在开头,中间和结尾处的.*强制其与整个字符串匹配,以便替换文本消除您所需要的内容.

I'm looking for a regex to extract two numbers from the same text (they can be run independently, no need to extract them both in one go.

I'm using yahoo pipes.

Source Text: S$ 5,200 / month Negotiable, 1,475 sqft / 137 sqm (built-in) - Apartment, 10 Anson Road (D02)

Need to extract as a number: 1,475 and also (but can be extracted on a separate instance) Need to extract as a number: 137

I got the following pattern from someone quite helpful on a different forum:

\b(\d+(,\d+)*)\s+(sqft|sqm)

but when i go and use it with a replace $1, it brings back the whole source text instead of just the numbers i want (ie. 1,475 or 137 depending on whether i run \b(\d+(,\d+))\s+(sqft) or \b(\d+(,\d+))\s+(sqm)

what am i doing wrong?

解决方案

Well you could do this by iterating through the matches and getting the results that way.

But if you want to use the replace method then this could work:

^.*?(?<sqft>\d+(,\d+)*)\s?sqft.*?(?<sqm>\d+(,\d+)*)\s?sqm.*$

And then replace with:

${sqft}
${sqm}

Here it is in action.

This will work with or without a comma in the sqft or sqm numbers. And the .* at the beginning, middle, and end forces it to match the entire string so that the replacement text eliminates everything except for what you're after.

这篇关于使用正则表达式提取特定文本之前的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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