简体   繁体   English

正则表达式匹配从字符串中获取正确数字的简单逻辑

[英]Regular expression to match a simple logic of getting the proper digits from string

Here I have a several different strings with salaries:在这里,我有几个不同的带薪水的字符串:

"U3 000 Per Month"
"U10 000 - U12 000 Per Month"
"U12 000 Per Month"
"U125 000 - U130 000 Per Month"
"U130 000 Per Month"

I'm trying to build a regex using the following logic:我正在尝试使用以下逻辑构建正则表达式:

Match the first 1,2 or 3 digits that come after first U letter only, then match zeros that come after a single space after first 1,2 or 3 digit group.仅匹配一个U 字母后的1,2 或 3 位数字,然后匹配第一个1,2 或 3 位数字组后的单个空格后的零。 The rest of the string doesn't matter.字符串的其余部分无关紧要。 For example, we have few strings:例如,我们有几个字符串:

"U20 000 - U30 000 Per Month"
"U3 000 Per Month"
"U125 000 - U130 000 Per Month"

I want a regex to return我想要一个正则表达式返回

20000, 3000, 125000 20000、3000、125000

Please help, I'm too exhausted of digging Regex documentation请帮忙,我已经厌倦了挖掘 Regex 文档

You could try with (?<=^U)\\d{1,3}\\s0* .你可以试试(?<=^U)\\d{1,3}\\s0*

regex = /(?<=^U)\d{1,3}\s0*/
p 'U20 000 - U30 000 Per Month'.scan(regex).first.sub(/\s/, '') # "20000"
p 'U3 000 Per Month'.scan(regex).first.sub(/\s/, '') # "3000"
p 'U125 000 - U130 000 Per Month'.scan(regex).first.sub(/\s/, '') # "125000"

I thought in only zeros after the \\s , so as you've added \\d{1,3} would fit better.我认为\\s之后只有零,所以你添加了\\d{1,3}会更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM