質問

To format properly data from third party service, I was wondering if this regex is concise enough:

(([\d,.]+))(1?\sR\$)

to change this:

from 200 R$ to 400 R$ (32 products)

into this:

from R$ 200 to R$ 400 (32 products)

to format this output, I am using Preg to replace the text with $3 $1 , as seen in http://www.regextester.com/

is this good enough or the regex is not adequate?

役に立ちましたか?

解決

Regex: (\d+[.,]?\d*)(\s*)(R\$)

Replacement: $3$2$1


Test input:

from 200 R$ to 400 R$ (32 products)
from 0,200 R$ to 0.400 R$ (32 products)
from 2,00 R$ to 4.00 R$ (32 products)

Test output:

from R$ 200 to R$ 400 (32 products)
from R$ 0,200 to R$ 0.400 (32 products)
from R$ 2,00 to R$ 4.00 (32 products)

If you want to parse also decimal numbers with no leading zero, such as .200, then use regex

(?=[.,]?\d)(\d*[.,]?\d*)(\s*)(R\$)

他のヒント

  1. You can definitely remove the first set or brackets

    and replace with $2 $1

  2. What is the 1? good for? If there is a 1 at the end of the first group that would that would be matched by [\d,.]+, so it is also superfluous

  3. Don't take the \s into your capturing group, you will have then one to much in the result

So I think this would be your regex:

([\d,.]+)\s(R\$)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top