Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

re.error: unbalanced parenthesis at position 16

I have had problems using regular expressions in python. It gives me an error called "re.error: unbalanced parenthesis at position 16". I have been trying to solve it for a long time, but I am not able to find the error. According to me all parentheses are closed. Here is my code:

import re

line1= "Move 1 Move 2 Left Right"
matchA = re.fullmatch('[(Move\\s[0-9]+\\s)(Left\\s)(Right\\s)]+', line1)
print(matchA[0])

If someone can guide me I would be very grateful

EDIT: My goal is to match words or combinations of words (which are contained within []) with a string, in order to recognize if there are syntax errors. For example matching the phrase "Move 1 Move 2 Left Right " with the sets of words contained within []

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am looking for, for example, the algorithm to take as correct the combination "Move 1 Move 2 Left Right" or "Move 1 Left " or "Left Right " or "Move 1 Left Move 2 " and not, for example, the badly written combination "Mve 1 Mov 2 Let Rigt" or "Move 1 Left Rgt".

>Solution :

Below the regex I guess you are after:

import re

line1= "Move 1 Move 2 Left Right "
line2= "Move 2 Left Right "
line3= "Move 21 Move 42 Left Right "
matchA = re.fullmatch(r'(Move\s[0123456789]+\s)+(Left\s)(Right\s)', line1)
print(matchA[0]) # gives 'Move 1 Move 2 Left Right '
matchB = re.fullmatch(r'(Move\s[0123456789]+\s)+(Left\s)(Right\s)', line2)
print(matchB[0]) # gives 'Move 2 Left Right'
matchC = re.fullmatch(r'(Move\s[0123456789]+\s)+(Left\s)(Right\s)', line3)
print(matchC[0]) # gives 'Move 21 Move 42 Left Right '

A hint for future work with regular expressions: you can use https://regex101.com/ as a great help with writing regex expressions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading