2

I have long string S, and I want to find value (numeric) in the following format "Value(**)", where ** is values I want to extract.

For example, S is "abcdef Value(34) Value(56) Value(13)", then I want to extract values 34, 56, 13 from S.

I tried to use regex as follows.

import re
regex = re.compile('\Value(.*'))
re.findall(regex, S)

But the code yields the result I did not expect.

Edit. I edited some mistakes.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Gilseung Ahn
  • 2,343
  • 1
  • 3
  • 10
  • Only one of those values is preceded by `Value`. And your regex is looking for `Values`, not `Value` And parentheses in regex need to be escaped. – Nick Apr 10 '20 at 00:37

3 Answers3

0

You should escape the parentheses, correct the typo of Value (as opposed to Values), use a lazy repeater *? instead of *, add the missing right parenthesis, and capture what's enclosed in the escaped parentheses with a pair of parentheses:

regex = re.compile(r'Value\((.*?)\)')
blhsing
  • 77,832
  • 6
  • 59
  • 90
0

Only one of your numbers follows the word 'Value', so you can extract anything inside parentheses. You also need to escape the parentheses which are special characters.

regex = re.compile('\(.*?\)')
re.findall(regex, S)

Output:

['(34)', '(56)', '(13)']

Derek O
  • 11,124
  • 3
  • 19
  • 35
0

I think what you're looking for is a capturing group that can return multiple matches. This string is: (\(\d{2}\))?. \d matches an digit and {2} matches exactly 2 digits. {1,2} will match 1 or 2 digits ect. ? matches 0 to unlimited number of times. Each group can be indexed and combined into a list. This is a simple implementation and will return the numbers within parentheses. eg. 'asdasd Value(102222), fgdf(20), he(77)' will match 20 and 77 but not 102222.

Bugbeeb
  • 1,778
  • 7
  • 19