简体   繁体   English

正则表达式-左右字符数相等

[英]Regular expressions - Equal number of characters in left and right

So I have this regular expression 所以我有这个正则表达式

[a+][a-z-[a]]{1}[a+]

which will match string "aadaa" 它将匹配字符串"aadaa"

but it will also match string "aaaaaaaadaa" 但也会匹配字符串"aaaaaaaadaa"

Is there any way to force it to match only those strings in which left side a's and right side a's occurrence count should be same? 有什么方法可以强制它只匹配左侧a和右侧a的出现次数应该相同的那些字符串?

so that it will match only "aadaa" and not this "aaaaaaaadaa" 因此它将仅匹配"aadaa"而不匹配此"aaaaaaaadaa"

Edit 编辑

With the help of Peter's answer I could make it working, this is the working version for my requirement 借助彼得的回答,我可以使其正常运行,这是我需要的工作版本

(a+)[a-z-[a]]{1}\1

You can use a back reference , as follows: 您可以使用反向引用 ,如下所示:

 console.log(check("ada")); console.log(check("aadaa")); console.log(check("aaaaaaaadaa")); console.log(check("aaadaaaaaaa")); function check(str) { var re = /^(.*).\\1$/; return re.test(str); } 

Or to only match a 's and d 's: 或仅匹配ad

 console.log(check("aca")); console.log(check("aadaa")); console.log(check("aaaaaaaadaa")); console.log(check("aaadaaaaaaa")); function check(str) { var re = /^(a*)d\\1$/; return re.test(str); } 

Or to only match a 's that surround not-an- a : 或者只匹配a的周围没有-AN- a

 console.log(check("aca")); console.log(check("aadaa")); console.log(check("aaaaaaaadaa")); console.log(check("aaadaaaaaaa")); function check(str) { var re = /^(a*)[bz]\\1$/; return re.test(str); } 


I realize all the above is javascript , which was easy for quick demoing within the context of SO. 我意识到以上所有都是javascript ,在SO的上下文中可以轻松进行快速演示。

I made a working DotNetFiddle with the following C# code that is similar to all the above: 我使用以下与以上所有代码相似的C#代码制作了一个有效的DotNetFiddle

public static Regex re = new Regex(@"^(a+)[b-z]\1$");

public static void Main()
{
    check("aca");
    check("ada");
    check("aadaa");
    check("aaddaa");
    check("aadcaa");
    check("aaaaaaaadaa");
    check("aadaaaaaaaa");
}

public static void check(string str)
{
    Console.WriteLine(str + " -> " + re.IsMatch(str));
}

You can also use the following regex for the same although I would prefer the one suggested by @PeterB 您也可以使用以下正则表达式,尽管我希望使用@PeterB建议的正则表达式

 console.log(check("aca")); console.log(check("aadaa")); console.log(check("aaaaaaaadaa")); console.log(check("aaadaaaaaaa")); function check(str) { var re = /^(\\w+)[A-Za-z]\\1$/; return re.test(str); } 

The code is similar to the one in Peter B's answer, but the regex is the one changed by me. 该代码与Peter B的答案中的代码相似,但是regex是我更改的代码。

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

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