Marc Wang
Marc Wang

Reputation: 171

RegEx javascript match 2 consecutive occurence of character but not more

I need help with regex. I have to match "{{" at the beginning of the string but not "{{{". I tried to use ^[{]{2} but it matches for "{{{". I tried to match "{{{" with ^[^{]{3} but I don't know how to match "{{" again.

I know I can probably get around it with a if statement. But I would like to do it in one shot within regex. Any Idea?

Upvotes: 0

Views: 231

Answers (2)

user663031
user663031

Reputation:

Use negative lookahead:

const re = /^{{(?!{)/;

console.log("{{{".match(re));
console.log("{{a".match(re));

Upvotes: 1

abc123
abc123

Reputation: 18763

Regex101

^{{[^{] or ^[{]{2}[^{] both will work

Description

^ asserts position at start of a line
{{ matches the characters {{ literally (case sensitive)
Match a single character not present in the list below [^{]
    { matches the character { literally (case sensitive)

Upvotes: 1

Related Questions