[英]Regex (python): how to match for certain query
I have a string list where every line is like this:我有一个字符串列表,其中每一行都是这样的:
1.alfa.america.game
1.alfa.america.game
i need to query this line with different parameters, and if matches, print it.我需要用不同的参数查询这一行,如果匹配,打印出来。 with this example, i get all the lines which have "1" and "db", but also get others, ie:
在这个例子中,我得到了所有有“1”和“db”的行,但也得到了其他的,即:
11.alfa.cad.base
11.alfa.cad.base
i don't want to get lines with "11" nor "db", only the exact match.我不想得到带有“11”或“db”的行,只有完全匹配。 this is what i did:
这就是我所做的:
code:代码:
ID = "1"
task = "db"
environment = "a-z"
location = "a-z"
fullString = "1.alfa.america.game" #this string can change
q = re.compile(r'(['+ID+'])+.(['+task+'])+.(['+environment+'])+.(['+location+'])+.', flags=re.I | re.X)
m = q.match(fullString)
if m:
print (fullString)
thanks in advance!提前致谢!
A few notes about the pattern, some of which are already mentioned in the comment.关于模式的一些注释,其中一些已经在评论中提到。
With the current variables, the pattern would be使用当前变量,模式将是
([1])+.([db])+.([a-z])+.([a-z])+.
.
.
matches any character instead of a dot only.()+
would capture the value of the last iteration, you want the group value as a whole so you can repeat the character class instead()+
将捕获最后一次迭代的值,您希望将组值作为一个整体,因此您可以重复字符 class1
and db
are hardcoded, you don't really have to capture them1
和db
这样的字符串是硬编码的,因此您实际上不必捕获它们Taking that into account, you could use 2 capturing groups instead.考虑到这一点,您可以改用 2 个捕获组。 As you are using re.match you can omit the anchor at the start and assert the end of the string using
\Z
当您使用re.match时,您可以省略开头的锚点并使用
\Z
断言字符串的结尾
1\.db\.([a-z]+)+\.([a-z]+)\Z
^ ^ ^
Dot group 1 group 2
q = re.compile(ID+r'\.'+task+'\.(['+environment+']+)+\.(['+location+']+)\Z', flags=re.I)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.