I have a regex /^\[(text:\s*.+?\s*)\]/mi
that currently works in capturing text in brackets that begin with text:
. Here is an example where it works:
[text: here is my text that is
captured within the brackets.]
Now, I would like to add an exception so that it allows certain brackets like in the case below:
[text: here is my text that is
captured within the brackets
and also include ![](/some/path)]
Basically, I need it to allow the ![](/some/path)
brackets in the match.
Any help would be greatly appreciated. Thanks.
Update:
Here are some cases where the text inside the brackets should be matched:
[text: here is my text that is
captured within the brackets
and also include ![](/some/path)]
[text: here is my text that is
captured within the brackets
and also include ![](/some/path) and some more text]
[text: ![](/some/path)]
![text: cat]
Here are some cases where it should not match:
[text: here is my text that is
captured within the brackets
and also include ![invalid syntax](/some/path)]
[text: here is my text that is
captured within the brackets
and also include ![] (/some/path)]
[text: here is my text that is
captured within the brackets
and also include ! [](/some/path)]
[text: here is my text that is
captured within the brackets
and also include ! [] (/some/path)]
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
Well, you can just add them to the regex with something like [0-9. \)\(-]+ but, since you're complicating the expression, you'll probably need to check for balance as well. In other words, that regex is quite happy to accept 74.7((((((((((((2) which is not really well-formed.
Python Regex Escape Parentheses () You can get rid of the special meaning of parentheses by using the backslash prefix: \( and \) . This way, you can match the parentheses characters in a given string.
The special characters are: a. ., *, [, and \ (period, asterisk, left square bracket, and backslash, respectively), which are always special, except when they appear within square brackets ([]; see 1.4 below). c. $ (dollar sign), which is special at the end of an entire RE (see 4.2 below).
OK, so you want to allow either
![]
between the starting and ending bracket. This gives you the regex
/^\[(text:[^\[\]]*(?:!\[\][^\[\]]*)*)\]/mi
Explanation:
^ # Start of line
\[ # Match [
( # Start of capturing group
text: # Match text:
[^\[\]]* # Match any number of characters except [ or ]
(?: # Optional non-capturing group:
!\[\] # Match ![]
[^\[\]]* # Match any number of characters except [ or ]
)* # Repeat as needed (0 times is OK)
) # End of capturing group
\] # Match ]
Test it live on regex101.com.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With