-2

Need to match only the first pair of curly brackets (and the following semicolon).

tried regex /({.*};)/

String example - {text 1}; {text 2};

Expected result {text 1};

Current result {text 1}; {text 2};

Adding ? doesnt seem to work here - /({.*};?)/

Thanks

bigInt
  • 173
  • 2
  • 13
  • 1
    Omit the `g` from `/g` which matches all occurrences – The fourth bird Sep 09 '20 at 08:49
  • Ah, ok, was playing on Regex Pal - cant remove from there, I think :) Thanks, will try – bigInt Sep 09 '20 at 08:49
  • @The fourth bird - for some reason it doesnt work – bigInt Sep 09 '20 at 09:01
  • I forgot, you also have to make the quantifier non greedy `{.*?};` or like this `{[^{}]*};` – The fourth bird Sep 09 '20 at 09:03
  • Thanks. Would you mind to provide an answer? Maybe even with explanation what "greedy" supposed to be meaning? :) Example I provided was simplified, so i still need to adopt it... – bigInt Sep 09 '20 at 09:04
  • 2
    It is asked frequently, and I am sure there are duplicates. But you can read about it for example here https://www.regular-expressions.info/repeat.html and here https://www.rexegg.com/regex-quantifiers.html or here at the **Quantifiers** section https://stackoverflow.com/a/22944075/5424988 – The fourth bird Sep 09 '20 at 09:09

1 Answers1

0

A lone * is called a greedy operator, because it will try to match as much of the source as possible: in your case, up to the second }.

You can use the lazy operator *?, which will match as short as possible, here up to the first }.

Like such:

/({.*?};)/

Or you can use a character set, noted with square brackets, that excludes the closing bracket: [^}] (the ^ negates the content of the set) instead of the dot:

/({[^}]*};)/

(I personnally prefer this solution because it is more explicit as to which characters are allowed/restricted from the match, but in your case it's a simple matter of taste).

Your suggestion of adding a ? after the semicolon is not relevant because it will only apply to the semicolon, not the whole group.

joH1
  • 463
  • 1
  • 6
  • 18
  • 2
    [398](https://stackoverflow.com/questions/linked/22444?lq=1) + [53](https://stackoverflow.com/questions/linked/2503413?lq=1) same questions have already been answered. Next time, please consider flagging such questions as duplicates. – Wiktor Stribiżew Sep 09 '20 at 09:15