简体   繁体   English

用双引号或单引号引起来的正则表达式字符串

[英]regex string enclosed by double quote or single quotes

I got this regex: 我得到这个正则表达式:

(\s|'|\")((?=.*[0-9])(?=.*[a-zA-Z]))([a-z0-9]{8})(\s|'|\")

to search for strings of length 8 having one lower case character and one digit. 搜索具有一个小写字符和一位数字的长度为8的字符串。 The string needs to be enclosed by space, quote or double quote. 字符串需要用空格,双引号或双引号引起来。

What does not work in the expression: something like this would be accepted: "1234567a' . If string starts with ' it should end with ' , when starting with " it should end by " etc. 那些不能表达工作:这样的事情会被接受: "1234567a' 。如果字符串的开头是'它应该结束' ,与启动时"应该通过结束"等。

I am not very strong at regexes so let me ask if there is a better way to enforce same character for begin and end without repeating regex 3 times? 我对正则表达式的能力不是很强,所以请问是否有更好的方法可以在不重复正则表达式3次的情况下对开始和结束执行相同的字符?

If you want to match the same char at the end of the string as the one at its start, you may use a backreference to the char once it is captured into a capturing group. 如果要在字符串的末尾与字符串的开头匹配相同的字符,则在将字符捕获到捕获组中后,可以对它使用反向引用

Besides, to make sure you match at the start of the string, add ^ anchor at the start of the string and $ anchor at the end of string: 此外,要确保您在字符串的开头匹配,请在字符串的开头添加^锚,在字符串的末尾添加$锚:

r'''^([\s'"])(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]{8}\1$'''

See the regex demo 正则表达式演示

The ([\\s'"]) is a capturing group with ID 1, so, the \\1 backreference at the end matches the same text as is stored in Group 1 memory buffer. ([\\s'"])是ID为1的捕获组,因此,末尾的\\1反向引用与第1组内存缓冲区中存储的文本匹配。

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

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