正则表达式python条件 [英] regex python conditions

查看:50
本文介绍了正则表达式python条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 tkinter 编写了一个应用程序.现在我想在用户使用它时在输入框中添加条件/模式.我想强制用户使用这些模式:

I coded an app with tkinter. Now I want to add conditions/pattern in a entry box when the user use it. I want to force the user to use these pattern:

The entry must begin by this pattern `^#\d+\s[A-I]\d+(,|;|-|)`
if there is a `,` or `-` in the string, the pattern must be the same plus `[A-I]\d+`
If there is `;` in the string, redo the first pattern
if after  `^#\d+\s[A-I]\d+(,|;|-|)` there is nothing, do nothing
I used regex conditions but nothing happened. 
I use this `^#\d+\s[A-I]\d+(,|;|-|)(?:(?=,)[A-I]\d+)`

我用这个程序来检查我的正则表达式

I use this program to check my regex expression

user = input("Please enter user : ")
while not re.match(r"#\d+\s[A-Z]\d+(?:[,-][A-Z]\d+)*(?:;#\d+\s[A-Z]\d+(?:[,-][A-Z]\d+)*)*", user):
    print ("Error! ")
    user = input("user : ")
print("user "+ user)

推荐答案

注意[AI]Q7中的Q不匹配.您可以使用 [A-Z] 扩展范围并为第一个和第二个模式使用重复组.

Note that [A-I] does not match the Q in Q7. You can use [A-Z] to extend the range and use a repeating group for the first and the second pattern.

你可能会使用

#\d+\s[A-Z]\d+(?:[,-][A-Z]\d+)*(?:;#\d+\s[A-Z]\d+(?:[,-][A-Z]\d+)*)*

模式匹配:

  • #\d+\s[A-Z]\d+ 匹配 # 1+ 个数字,一个空格字符和 1+ 个数字
  • (?:[,-][AZ]\d+)* 可选择重复匹配 ,- 字符 AZ 和 1+ 位数字
  • (?: 非捕获组
    • ;#\d+\s[A-Z]\d+ 匹配 ; 和第一个模式
    • (?:[,-][A-Z]\d+)* 可选择重复匹配第二个模式
    • #\d+\s[A-Z]\d+ Match # 1+ digits, a whitespace char and 1+ digits
    • (?:[,-][A-Z]\d+)* Optionally repeat matching , or - char A-Z and 1+ digits
    • (?: Non capture group
      • ;#\d+\s[A-Z]\d+ Match ; and the first pattern
      • (?:[,-][A-Z]\d+)* Optionally repeat matching the second pattern

      正则表达式演示

      或者如果您还想允许空格:

      Or if you want to allow spaces as well:

      #\d+\s[A-Z]\d+(?:[,-]\s?[A-Z]\d+)*(?:;#\d+\s[A-Z]\d+(?:[,-]\s?[A-Z]\d+)*)*
      

      正则表达式演示

      这篇关于正则表达式python条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆