-1

I am trying to extract the price from a string, but unable to fully complete the logic.

My String: (2) 1,127.22 abcdfg sdkjf 20,200.01 abcdfg sdfkgj (2) 10.28

What I want to do is:

to find all "(2)" in the string and then extract the full price next to it. 

My regex pattern is: "\d+(,\d{1,100})"

My pattern only finds 1,127, 20,200 10 in the big string and it also doesn't have the condition of checking if it is next to (2).

I want to get the full price: 1,127.22 and 10.28

EDIT:

Managed to get cents with the regex: \d+(,\d{1,100})(.\d\d?)

AlpU
  • 363
  • 1
  • 9
  • 26

4 Answers4

2

Your regex matches one or more digits \d+ and then in a captured group match a comma and a digit from 1 till 100 times. That matches 1,127 but not 1,127.22. As you mentioned, the is also no condition of checking if it is next to (2).

This regex could be an option to do it:

\(2\)\s(\d+[,.]\d+(?:[.]\d+)?)

Explanation

  • Match (2) \(2\)
  • Match a whitespace \s
  • A capturing group ( (This is where your values will be)
  • Match one or more digits, a comma or a dot and one or more digits \d+[,.]\d+
  • An optional non capturing group which matches a dot followed by on or more digits (?:[.]\d+)?
  • Close the capturing group

Output with C#

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

You can try this:

import re
s = "(2) 1,127.22 abcdfg sdkjf 20,200.01 abcdfg sdfkgj (2) 10.28"
vals = re.findall('(?<=\d\)\s)[\d\.,]+', s)

Output:

['1,127.22', '10.28']

If you want a list of floats, rather than strings:

vals = list(map(lambda x:float(re.sub(',', '', x)), re.findall('(?<=\d\)\s)[\d\.,]+', s)))

Output:

[1127.22, 10.28]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

(?<=\(2\))\s*((:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S))

Borrowed the num seq from here

Rafael
  • 7,605
  • 13
  • 31
  • 46
0

VB.NET answer without regex. Shows you how to play with strings

        Dim SplitStr As String() = New String() {"(2)"}
        Dim mystring As String = "(2) 1,127.22 abcdfg sdkjf 20,200.01 abcdfg sdfkgj (2) 10.28"

        Dim PriceList As New List(Of Decimal)
        For Each xItem In mystring.Split(SplitStr, StringSplitOptions.RemoveEmptyEntries)
            PriceList.Add(Convert.ToDecimal(xItem.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)(0)))
        Next
Chillzy
  • 468
  • 3
  • 9