0

I am using python to pattern match a string multiple times in a string. Problem:

string = 'The value = 1 The value = 2 The value = 3'

I want to grep only value but my output should be like:

['value = 1 value = 2 value = 3']

I am doing like this:

pattern = re.compile('[value = (\d+)]*')
values = pattern.search(string)
values.group(0)

Output:

'' 

i.e NULL (no match)

Please help me give the right regular expression to grep the required output.

5
  • 2
    There are no spaces between the = equals signs and the numbers in your input example, but your regular expression expects a space there. The output example is a single string in a list, did you mean to make that a list of 3 strings instead? Commented Nov 29, 2012 at 11:19
  • The string should be: string = 'The value = 1 The value = 2 The value = 3'. I am just keeping it. I am not sure whether list is involved or not... Commented Nov 29, 2012 at 11:21
  • Why are you having a * after your bracket? Commented Nov 29, 2012 at 11:22
  • It might match for multiple times... Commented Nov 29, 2012 at 11:23
  • As well as the answers you've got - a simple string.replace('The ', '') works in this case ;) Commented Nov 29, 2012 at 11:43

3 Answers 3

1
>>> [' '.join(re.findall(r'value = \d+', string))]
['value = 1 value = 2 value = 3']
Sign up to request clarification or add additional context in comments.

Comments

1

You are using a character class grouping. You should just use a normal grouping with (.

import re

string = 'The value = 1 The value = 2 The value = 3'

pattern = re.compile(r'(value = \d+)')
pattern.findall(string)
# OUT: ['value = 1', 'value = 2', 'value = 3']
" ".join(pattern.findall(string))
# OUT: 'value = 1 value = 2 value = 3'

Comments

0

Your use of square brackets ([]) in the RE source is very odd. Those form character sets.

You should use something like:

>>> pattern = re.compile(r'([^=]+)\s*=\s*(\d+)')
>>> pattern.findall(string)
[('The value ', '1'), (' The value ', '2'), (' The value ', '3')]

Note use of findall() to get all the matches, and grouping to get the value names too.

1 Comment

Thanks. But my output should be like one string: ['value = 1 value = 2 value = 3']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.