2

I am trying to use python's re to match a certain format.

import re
a = "y:=select(R,(time>50)and(qty<10))"   
b = re.search("=.+\(",a).group(0)
print(b) 

I actually want to select this portion"=select("from string a. but the code I have made outputs the answer as =select(R,(time>50)and(. I tried re.findall, but this too returns the same output. It does not notice the first match and only outputs the final match. Anywhere I'm going wrong? Your Help is greatly appreciated. I basically want to find the function name, in this case select. The strategy is used was appears after = and before (.

  • 1
    [Similar question and answer](https://stackoverflow.com/questions/766372/python-non-greedy-regexes) – DarrylG Dec 02 '19 at 05:25
  • 1
    regex is "greedy" - it tries to find the longest matching string. Using `?` like in answer it tries to find the shortest string. – furas Dec 02 '19 at 05:25

2 Answers2

4

You are missing '?' in your pattern, try this:

=.+?\(

Demo

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
2

Another method that works - you specify explicitly what you need:

import re
a = "y:=select(R,(time>50)and(qty<10))"   
# make sure your piece does not contain "("
b = re.search("=[^\(]+\(",a).group(0)
print(b) 
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20