Regex filter only values in real

Asked

Viewed 1,541 times

1

I have the following regex:

preg_match_all('/([0-9]+[\.]*[0-9]*[\,.]*[0-9]*)/', $string, $matches)

If I get a string:

1 - João da Silva number 123456 with the value of R$:6,298.65

I have as return:

array (size=27)
  0 => string '1' (length=1)
  1 => string '123456' (length=5)
  2 => string '6.298,65' (length=8)

However, I would like to return only the value in real: 6.298,65

  • If you add $ at the end of your regex, also works.

2 answers

3


The problem is you’re leaving everything as "optional" (*).
The REGEX that can help you is :

~R\$:[\t ]*(\d{1,3}\.?)+(,\d{2})?~

See in REGEX101

  • The problem is that the real value does not always come preceded by R$: , it can come without R$: (in the amount of 1,200,00) or come only with R$ (in the amount of R$1,200,00)

  • @Bia if always have cents can change to ((\d{1,3}\.?)+(,\d{2})), Behold.

3

I believe you’re looking for the pattern numero.numero,numero, I would make a regex thus:

/\d+\.\d+,\d+/
  • \d is a shorthand that searches for numbers, is the same as the set [0-9]
  • + is a quantifier searching for 1 or more elements is the same as {1,}
  • \. will look for a string because I used a \.

Running in jsFidlle and Running on regex101

If you need the text to start with you R$: you must add R\$: at the beginning of the regex, it is necessary to use the Scape\ because the $ is an edge that searches at the end of the text.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.