How to check if a string contains a number between two brackets and returns a location?

Say I have str = "qwop(8) 5" and I want to return position 8.

I have the following solution:

 import re str = "qwop(8) 5" regex = re.compile("\(\d\)") match = re.search(regex, string) # match object has span = (4, 7) print(match.span()[0] + 1) # +1 gets at the number 8 rather than the first bracket 

It seems really dirty. Is there a more complicated solution? It is preferable to use re , as I have already imported this for other purposes.

+5
source share
3 answers

Use match.start() to get the index of the beginning of the match, and a capture group to fix a specific digit between the brackets to avoid +1 in the index. If you want to start the template yourself, use match.start() ; if you only need a number, use match.start(1) ;

 import re test_str = 'qwop(8) 5' pattern = r'\((\d)\)' match = re.search(pattern, test_str) start_index = match.start() print('Start index:\t{}\nCharacter at index:\t{}'.format(start_index, test_str[start_index])) match_index = match.start(1) print('Match index:\t{}\nCharacter at index:\t{}'.format(match_index, test_str[match_index])) 

Outputs;

 Start index: 4 Character at index: ( Match index: 5 Character at index: 8 
+4
source

You can use:

 regex = re.compile( r '\( (\d+) \)') 

The prefix r means that we are working with a raw string. A raw string means that if you write, for example, r'\n' , Python will not interpret this as a string with a new string character. But like a string with two characters: backslash ( '\\' ) and 'n' .

Additional brackets are in the definition of the capture group. In addition, a number is a sequence (one or more) digits. Thus, + guarantees that we will also write (1425) .

Then we can execute a .search() and get a match. Then you can use .start(1) to get the start of the first capture group:

 >>> regex.search(data) <_sre.SRE_Match object; span=(4, 7), match='(8)'> >>> regex.search(data).start(1) 5 

If you are interested in the contents of the first capture group, you can call .group(1) :

 >>> regex.search(data).group(1) '8' 
+2
source
 import re s = "qwop(8)(9) 5" regex = re.compile("\(\d\)") match = re.search(regex, s) print(match.start() + 1) 

start () means the starting index, searching for the search query for the first entry. so this will only show index (8).

+2
source

Source: https://habr.com/ru/post/1269934/


All Articles