2

I want to extract each arithmetic formula from this string:

+100*25-30

I used this regex:

preg_match_all("/(([\*\+\-\/])([0-9]+\.?[0-9]*))+/", "+100*25-30", $match);

It is capturing only last occurrence which is -30 but if I enter space before operator like this: +100 *25 -30, it is capturing all correctly, but I should do it without space. How to do it?

Jamol
  • 3,768
  • 8
  • 45
  • 68
  • 1
    You have this `(...)+`. Just remove every thing except `...`. [See it in action](https://regex101.com/r/h0VnTG/1) – revo Dec 31 '20 at 16:14
  • @revo yes you are right. I understood it after seeing answer from Wiktor Stribiżew. – Jamol Dec 31 '20 at 16:19

1 Answers1

0

The (([\*\+\-\/])([0-9]+\.?[0-9]*))+ pattern is an example of a repeated capturing group. Since it matches the whole +100*25-30 string capturing each pair of the match operator with the number after it, only the last occurrence captured is stored in the Group 1 (that is -30).

You can use

preg_match_all("/([*+\/-]?)([0-9]+\.?[0-9]*)/", "+100*25-30", $match)

See the PHP demo. Alternatively, preg_match_all("/([*+\/-]?)([0-9]*\.?[0-9]+)/", "+100*25-30", $match).

See also the regex demo.

Details:

  • ([*+\/-]?) - Group 1: an optional *, +, / or - char
  • ([0-9]*\.?[0-9]+) - Group 2: zero or more digits, an optional . and one or more digits.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you very much. Now I understood one thing. + at the end of my regex was my mistake. If I remove + at the end, it is working. In your regex, you added ? after operators : [*+\/-]? Why is ? needed here? It is must to exist at least one operator. I think ? means zero or more correct? – Jamol Dec 31 '20 at 16:15
  • @Jamol I made the math operator optional. `?` matches 1 or 0 times, i.e. greedily, at least once, but the pattern can also go missing. If you do not use it, the number without an operator (say, at the start of a string) won't get matched. You might also consider `([*+\/-]|^)` instead of `([*+\/-]?)` if you need to explicitly match at the start of string or an operator. – Wiktor Stribiżew Dec 31 '20 at 17:58