Home > Software engineering >  How to create a RegEx for something like {{example:bool}}
How to create a RegEx for something like {{example:bool}}

Time:01-20

I'm creating shortcodes inside an Angular application. To replace the content I'm using regular expressions.

Replacing shortcodes like {{example}} to get "example" is working well. For that I'm using the following regex:

/\{ ([^\][] ?)} /g

But now the challenge. What if I have a shortcode with this structure: {{example:bool}}. I need "example" also in this case. What I tried is not working. This is my version:

/\{ ([^\][] ?):bool} /g

But seems to be the wrong way... I also tried it with helper pages like regex101. But everything I try is not the solution I need. I really want to understand this. So if you answer this question, would be awesome to get also an explanation for it. Thanks in advance!

CodePudding user response:

The main thing about matching some strings between two different characters when another string is between them is to exclude the delimiter chars. You exclude [ and ] betweeen { and } while you should be excluding the braces themselves.

So, you may use either

{ ([^{}:]*)(?::([^{}]*))?} 

(see demo) if you plan to match and capture any string inside {...} before the first colon (if any) into Group 1 and the part after : into Group 2 (again, if any).

If you plan to match a specific word/string at the end of the {...} string just use it as part of the regex (you can freely use any literal text as part of the regex):

{ ([^{}:]*):bool} 
{ ([^{}:]*)(?::([^{}]*))?:bool} 

See this regex demo and this regex demo.

The first regex here matches the same way as the first regex in the answer but the part with : is not optional. The second regex here matches a second : part optionally, before :bool obligatory part.

Details (last regex):

  • { - one or more { chars
  • ([^{}:]*) - Group 1: any zero or more chars other than { and }
  • (?::([^{}]*))? - an optional sequence of
    • : - a colon
    • ([^{}]*) - Group 2: any zero or more chars other than { and }
  • :bool - a literal text
  • } - one or more } chars.
  •  Tags:  
  • Related