Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match first instance of Python regex search

Tags:

I'm looking to the first instance of a match two square brackets using regular expressions. Currently, I am doing

regex = re.compile("(?<=(\[\[)).*(?=\]\])") r = regex.search(line) 

which works for lines like

[[string]]  

returns string

but when I try it on a separate line:

[[string]] ([[string2]], [[string3]]) 

The result is

string]] ([[string2]], [[string3 

What am I missing?

like image 639
Rio Avatar asked Feb 22 '11 05:02

Rio


People also ask

How do you search for a regex pattern at the beginning of a string Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

How do you match the beginning of a string in Python?

Python Re Start-of-String (^) Regex. You can use the caret operator ^ to match the beginning of the string. For example, this is useful if you want to ensure that a pattern appears at the beginning of a string.

How do you check if a string matches a regex pattern in Python?

Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list.

What is match () function in Python?

match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none.


1 Answers

Python *, +, ? and {n,m} quantifiers are greedy by default

Patterns quantified with the above quantifiers will match as much as they can by default. In your case, this means the first set of brackets and the last. In Python, you can make any quantifier non-greedy (or "lazy") by adding a ? after it. In your case, this would translate to .*? in the middle part of your expression.

like image 138
Drew Avatar answered Nov 04 '22 17:11

Drew