Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex – Match all charactes between curly braces as long as certain string is present

I have paragraphs like this:

"{~1.6} This is another paragraph {~1} with curly braces.{~6.8}"

I want to match {~<int or float>}

So far I’ve came to this regex: /\{(\~(\d*\.?\d+),?)\}/g

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It works just fine but sometimes there will be some other characters before or after ~<int or float> like this:

"{:.class ~1.6 #id} This is another paragraph {~1 .class #id} with curly braces.{:#id ~6.8}"

I don’t know in advance the content before or after ~<int or float>, all that I know is that all the content is between curly braces.

How can I match every {<some content here>} as long as it contains at least one ~<int or float> occurrence?

>Solution :

/{([^}]*(~\d*(?:\.\d+)?)[^}]*)}/

Match the brace, any number of non-brace characters, then the bit you were interested in (tilde and a number, with optional decimal point and decimal digits), then possibly some more non-brace characters, and finally the closing brace. regex101

Note that a brace does not need to be escaped in JavaScript unless it contains a valid quantifier (number or pair of numbers separated by a comma, possibly with one number missing), though it doesn’t hurt; tilde does not need escaping at all.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading