ron*_*ook 5 python regex string parsing python-3.x
说我有str = "qwop(8) 5",我想要返回8的位置.
我有以下解决方案:
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
Run Code Online (Sandbox Code Playgroud)
这看起来非常混乱.有更复杂的解决方案吗?最好使用re我已导入的用于其他用途.
用于match.start()获取匹配的开始索引,并使用捕获组来专门捕获括号之间的数字以避免+1索引中的数字。如果您想要模式的开头,请使用match.start(); 如果您只想要数字,请使用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]))
Run Code Online (Sandbox Code Playgroud)
输出;
Start index: 4
Character at index: (
Match index: 5
Character at index: 8
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1528 次 |
| 最近记录: |