have a regex match 'a-a' and 'b-b', but not 'a-b'?

Viewed 138

this is a really hard question to phrase, but is there a way to have a regex match 'a-a' and 'b-b', but not 'a-b'? basically i want it to match with the same character either side of a middle character (such as '-') but that said character is interchangeable with other characters in a set of characters (such as [abc]). I'd like the solution to be not brute forced as the set of characters i have in mind is quite large, and the answer should be in javascript

1 Answers

The pattern you are looking for is /^([a-c])-\1$/

You may reference any captured group through a \number syntax, where number is the number of your group, starting from 1.

Tests:

const pattern = /^([a-c])-\1$/;

pattern.test('a-a'); // true
pattern.test('b-b'); // true
pattern.test('c-c'); // true
pattern.test('a-b'); // false
Related