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
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?
4
Answers
You can try this one
You can surround your
~number
with classes excluding pairing braces, like this:Example here.
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.
To remove all characters that are outside of the curly braces, you can use the following regular expression:
{[^{}]*}
This pattern will take your example strings and output the following:
"{~1.6}{~1}{~6.8}"
"{:.class ~1.6 #id}{~1 .class #id}{:#id ~6.8}"
The pattern above is simpler but you can use this expression if you also need to ignore empty braces, ie
{}
{[^{}]*}(?=[^{}]*{[^{}]*})