[javascript] How to make Regular expression into non-greedy?

I'm using jQuery. I have a string with a block of special characters (begin and end). I want get the text from that special characters block. I used a regular expression object for in-string finding. But how can I tell jQuery to find multiple results when have two special character or more?

My HTML:

<div id="container">
    <div id="textcontainer">
     Cu?c chi?n pháp lý gi?a [|co th?|nghi?m|] th? tru?ng [|test2|dây là test l?n 2|] ch?ng khoán [|M?|day la nuoc my|] và ngân hàng d?u tu quy?n l?c nh?t Ph? Wall m?i ch? b?t d?u.
    </div>
</div>

and my JavaScript code:

$(document).ready(function() {
  var takedata = $("#textcontainer").text();
  var test = 'abcd adddb';
  var filterdata = takedata.match(/(\[.+\])/);

  alert(filterdata); 

  //end write js 
});

My result is: [|co th?|nghi?m|] th? tru?ng [|test2|dây là test l?n 2|] ch?ng khoán [|M?|day la nuoc my|] . But this isn't the result I want :(. How to get [text] for times 1 and [demo] for times 2 ?


I've just done my work after searching info on internet ^^. I make code like this:

var filterdata = takedata.match(/(\[.*?\])/g);
  • my result is : [|co th?|nghi?m|],[|test2|dây là test l?n 2|] this is right!. but I don't really understand this. Can you answer my why?

This question is related to javascript regex filter expression regex-greedy

The answer is


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:

/(\[[^\]]+\])/

See also


Quick summary

*   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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to filter

Monitoring the Full Disclosure mailinglist Pyspark: Filter dataframe based on multiple conditions How Spring Security Filter Chain works Copy filtered data to another sheet using VBA Filter object properties by key in ES6 How do I filter date range in DataTables? How do I filter an array with TypeScript in Angular 2? Filtering array of objects with lodash based on property value How to filter an array from all elements of another array How to specify "does not contain" in dplyr filter

Examples related to expression

How do I remove all non-ASCII characters with regex and Notepad++? SSRS Expression for IF, THEN ELSE Regex to get the words after matching string Regular expression to match a word or its prefix SSIS expression: convert date to string Are complex expressions possible in ng-hide / ng-show? Change some value inside the List<T> XPath - Difference between node() and text() javascript - match string against the array of regular expressions Spring cron expression for every after 30 minutes

Examples related to regex-greedy

How to capture multiple repeated groups? How can I write a regex which matches non greedy? Regex credit card number tests What is the difference between .*? and .* regular expressions? How to do a non-greedy match in grep? How to make Regular expression into non-greedy? What do 'lazy' and 'greedy' mean in the context of regular expressions? How can I make my match non greedy in vim? Non greedy (reluctant) regex matching in sed? Python non-greedy regexes