简体   繁体   English

正则表达式(python):如何匹配某些查询

[英]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])+.
  • Here, the .在这里, . matches any character instead of a dot only.匹配任何字符而不是仅匹配点。
  • If you don't want to match 11, you should not use a quantifier for either the group or the character class如果您不想匹配 11,则不应为组或字符 class 使用量词
  • Repeating the capture group ()+ would capture the value of the last iteration, you want the group value as a whole so you can repeat the character class instead重复捕获组()+将捕获最后一次迭代的值,您希望将组值作为一个整体,因此您可以重复字符 class
  • As strings like 1 and db are hardcoded, you don't really have to capture them由于像1db这样的字符串是硬编码的,因此您实际上不必捕获它们

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

Regex demo正则表达式演示

q = re.compile(ID+r'\.'+task+'\.(['+environment+']+)+\.(['+location+']+)\Z', flags=re.I)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM