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:
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
:
console.log(check("aca"));
console.log(check("aadaa"));
console.log(check("aaaaaaaadaa"));
console.log(check("aaadaaaaaaa"));
function check(str) {
var re = /^(a*)[b-z]\1$/;
return re.test(str);
}
I realize all the above is javascript, which was easy for quick demoing within the context of SO.
I made a working DotNetFiddle with the following C# code that is similar to all the above:
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));
}