正则表达式python条件

编程入门 行业动态 更新时间:2024-10-24 17:32:11
本文介绍了正则表达式python条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 06:10:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390595.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   正则表达式   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!