在python regex中使用OR的最佳方法是什么 [英] What is the best way to use OR in python regex
问题描述
我正在做关于正则表达式的作业,但在使用 OR
时遇到了一些困难.给定以下字符串:
avc7fsrd5vcc12vfscsrwt1qw7eetrs&fsrsy
<块引用>
应该返回 t1 s
fdjhads jhf&5672t3zcxvb,m654godjhfjdyeuyr123jfjjdjfjdfj77djsfhdjhfdsf99
<块引用>
应该返回 t3 go 123 77
第一部分是提取带有一些数字的 t ,然后提取 s 或 go 取决于先出现的内容.如果它通过,那么我们需要在之后提取两个数字,否则停止.
这是我正在使用的正则表达式
'(t[0-9]).*?(go).*?([0-9]+).*?([0-9]+)|(t[0-9]]).*?(s)'
但是当我将 s 添加到第二个字符串并提取 go 而不是 s 时,它不起作用.
任何帮助将不胜感激.
我认为这是您需要的正则表达式:
(t\d+).*?(go|s)\D*?(\d*)\D*?(\d*)
如果我正确理解您的问题,它会按照您的要求工作.
第一场比赛的演示:http://regexr.com/3coi0
第二场比赛演示:http://regexr.com/3coht
有关理解高级正则表达式的更多帮助,我建议您阅读https://www.talentcookie.com/2015/07/lets-practice-正则表达式https://www.talentcookie.com/2016/01/一些有用的正则表达式术语/
I'm doing an homework on regex and having some difficulties with OR
.
Given the following strings:
avc7fsrd5vcc12vfscsrwt1qw7eetrs&fsrsy
should return t1 s
fdjhads jhf&5672t3zcxvb,m654godjhfjdyeuyr123jfjjdjfjdfj77djsfhdjhfdsf99
should return t3 go 123 77
The first part is to extract t with some number and then extract s or go depending on what comes first. If its go, then we need to extract two numbers afterward, otherwise stop.
This is the regex I'm using
'(t[0-9]).*?(go).*?([0-9]+).*?([0-9]+)|(t[0-9]).*?(s)'
but it doesn't work when I add an s to the second string and extracts go instead of s.
Any help would be appreciated.
I think this is the regex you need:
(t\d+).*?(go|s)\D*?(\d*)\D*?(\d*)
It works as per your requirement if i understood you question properly.
Demo for 1st match: http://regexr.com/3coi0
Demo for 2nd match : http://regexr.com/3coht
For more help in understanding advance regex, i'd refer you to read https://www.talentcookie.com/2015/07/lets-practice-regular-expression https://www.talentcookie.com/2016/01/some-useful-regular-expression-terminologies/
这篇关于在python regex中使用OR的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!