The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex. By using a lazy quantifier, the expression tries the minimal match first.
It means the greedy quantifiers will match their preceding elements as much as possible to return to the biggest match possible. On the other hand, the non-greedy quantifiers will match as little as possible to return the smallest match possible. non-greedy quantifiers are the opposite of greedy ones.
About Non-Greedy Search The Non-Greedy search makes it possible to identify the target element from a pool of similar applications, matching the attributes you specify. It needs to be included in the top-level tag of a selector. If a generated selector contains the idx attribute, its value is set by default to * .
Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.
The non-greedy regex modifiers are like their greedy counter-parts but with a ?
immediately following them:
* - zero or more
*? - zero or more (non-greedy)
+ - one or more
+? - one or more (non-greedy)
? - zero or one
?? - zero or one (non-greedy)
You are right that greediness is an issue:
--A--Z--A--Z--
^^^^^^^^^^
A.*Z
If you want to match both A--Z
, you'd have to use A.*?Z
(the ?
makes the *
"reluctant", or lazy).
There are sometimes better ways to do this, though, e.g.
A[^Z]*+Z
This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.
In your case, the regex would be:
/(\[[^\]]++\])/
Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:
/(\[[^\]]+\])/
* Zero or more, greedy
*? Zero or more, reluctant
*+ Zero or more, possessive
+ One or more, greedy
+? One or more, reluctant
++ One or more, possessive
? Zero or one, greedy
?? Zero or one, reluctant
?+ Zero or one, possessive
Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m}
constructs.
Examples in Java:
System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!")); // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"
System.out.println("xxxxxx".replaceAll("x{3,5}", "Y")); // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
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