Regular expression for finding currency values but not dates in text

前端 未结 3 509
误落风尘
误落风尘 2021-01-29 07:18

I have text like the following two example strings

this book was sold for 12.00 on 12.12.2010
he paid 12.12.2010 , and puchased an amount of 15.00
相关标签:
3条回答
  • 2021-01-29 08:11

    You could use

    \d+\.\d{2}(?![.\d])
    

    if all you need is to distinguish between dates in exactly this format and currency amounts in exactly this format.

    This regex looks for the pattern digits, dot, two-digits but only if it's not followed by either another dot or another digit (to prevent the dates from matching).

    Quick PowerShell test:

    enter image description here

    Update for short dates in the form dd.mm.yy (just in case you need them):

    (?<![.\d])\d+\.\d{2}(?![.\d])
    

    enter image description here

    0 讨论(0)
  • 2021-01-29 08:11

    Try this

    \b\d+\.\d{2}(?!\.?\d)
    

    See it here on Regexr

    \b is a word boundary, this ensures that there is a non word character (includes also digits) before the first digit.

    \d+\.\d{2} is at least one digit, followed by a dot and two other digits.

    (?!\.?\d) is a negative look ahead that ensures that there is no digit OR no dot followed by a digit ahead. This would allow the amount to be at the end of the sentence.

    Working c# code:

    String s = "this book was sold for 12.00 on 12.12.2010";
    
    Regex r = new Regex(@"\b\d+\.\d{2}(?!\.?\d)");
    
    Console.WriteLine(r.Matches(s)[0]);
    Console.ReadLine();
    
    0 讨论(0)
  • 2021-01-29 08:22

    Try this one:

    (?:\s|^)\d+\.\d+(?:\s|$)
    

    It gives two matches in my test:

    12.00 
    15.00
    
    0 讨论(0)
提交回复
热议问题