简体   繁体   English

正则表达式用于将字符串与红宝石中的数字匹配

[英]regex for matching a string with a number in ruby

I have a string as below. 我有一个字符串如下。

"Included in PTA fees" or "Included in PTA fees 33$" or "Included in PTA fees $60"

I need to match this string with searching for PTA fee/fees and whether any fee(number) is also appended with it. 我需要将此字符串与搜索PTA费用相匹配,并且是否还要附加任何费用(数字)。

Need to look for "PTA fees" along with fee value in any given string and return true. 需要在任何给定的字符串中查找“ PTA费用”以及费用值,然后返回true。

So it should return true for 所以它应该返回true

"Included in PTA fees 33$" and
"Included in PTA fees $60"

It should return false for "Included in PTA fees" 对于"Included in PTA fees" ,应返回false

I tried with below regular expression. 我尝试使用下面的正则表达式。 but it returns true for 但它返回true

"Included in PTA fees"

/#{PTA_FEE[0-9]}/i.match?(value)

This regex should work 这个正则表达式应该工作

^.*PTA fees?(?=.*(?:(?:\d+\s*\$)|(?:\$\s*\d+)))

Regex Breakdown 正则表达式分解

(?i) #Ignore Case
^ #Start of string
.*
PTA fees? #Match the string with fee(s)
(?=.* #Lookahead

  (?: #Non capturing group

     (?:\d+\s*\$) #Match digit followed by $

        | #Alternation

     (?:\$\s*\d+) #Match $ followed digit

  ) #End non capturing group
) #End lookahead

rubular demo

You simply need \\S+ as end part of your regex: 您只需要\\S+作为正则表达式的结尾部分:

str =~ /Included in PTA fees? \S+/
  • \\S+ One or more non-whitespace character(s) \\S+一个或多个非空白字符
  • ? Optional match 选配

or to be more precise: 或者更确切地说:

str =~ /Included in PTA fees? (?:\d+\$|\$\d+)/

Live demo 现场演示

I'd go with Included in PTA fees(?=.*?(\\d+(?:\\.\\d+)?)) ; 我会选择Included in PTA fees(?=.*?(\\d+(?:\\.\\d+)?)) ; this also groups the fee and takes into account floating-point values. 这也将费用分组并考虑浮点值。 But it doesn't take into account any free-form negation such as " aren't included in PTA fees" or " not included in PTA fees". 但是它没有考虑任何自由形式的否定,例如“ 包含在PTA费用中”或“ 包含在PTA费用中”。

It disregards the dollar sign; 它无视美元符号; since your description is incomplete and what you're matching against looks like something that is potentially grammatically incorrect, you may have \\$\\s*\\d+|\\d+\\s*\\$ for the dollar sign. 由于您的描述不完整,并且您要匹配的内容看起来可能在语法上不正确,因此美元符号可能有\\$\\s*\\d+|\\d+\\s*\\$ Does the dollar value potentially have a thousand separator? 美元价值可能有千位分隔符吗?

You can complicate the answer to this question quite a lot when the problem is under-specified. 如果未明确说明问题,则可以使该问题的答案复杂得多。

You can use this one: 您可以使用以下一种:

^Included in PTA fees\s*(\$\d+|\d+\$)

It checks if string starts with Included in PTA fees and then allows fee number with a dollar sign before ( \\$\\d+ ) or after it ( \\d+\\$ ) 它检查字符串是否Included in PTA fees开头,然后允许费用编号在( \\$\\d+ )之前或之后( \\d+\\$ )加上美元符号

Demo 演示版

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

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