How do I combine 2 regex patterns into 1 and use i

2019-08-19 09:19发布

I have a regEx for checking a number is less than 15 significant figures, Borrowed from this SO answer

  1. /^-?(?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=.{1,16}0*$)(?:\d+[.,]\d+)‌​)).+$/

The the other is used to check that same number is upto 2 decimal places(truncate)

  1. /^-?(\d*\.?\d{0,2}).*/

I have almost 0 regex skill.

Question: How do I combine the 2 regexes to do the work of both, AND not just either OR( accomplished by | character - i am not sure if it achieves same function as combining both)

something like:

/^-?(?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=.{1,16}0*$)(?:\d+[.,]\d+)‌​)).+$ <AND&&NOTOR>(\d*\.?\d{0,2}).*/

Thanks in advance

EDIT: edit moved to a seperate SO question

1条回答
仙女界的扛把子
2楼-- · 2019-08-19 09:32

If you add only one condition of maximum 2 decimal places to first regex, try this..

^-?(?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=[,.\d]{1,16}0*$)(?:\d+[.,]\d{1,2}$))).+$

Demo,,, in which I only changed original \d+ to d{1,2}$

Edited for the reguest to extract 15 significant figures and capture group 1 ($1). Try this which is wrapped to capture group 1 ($1) and limited 15 significant figures to be extracted easily.

^(-?(?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=[,.\d]{1,16}0*$)(?:\d+[.,]\d{1,2}$))).{1,16}).*$

Demo,,, in which changed to .{1,16} from .+$. If the number matches, then able to be replaced $1, but if not so, replaced nothing, thus remains original unmatched number.

Therefore, if you want to extract 15 significant figures by replacing with $1 only when your condition is satisfied, try this regex to your function.

^(-?(?=\d{1,15}(?:[.,]0+)?0*$|(?:(?=[,.\d]{1,16}0*$)(?:\d+[.,]\d{1,2}$))).{1,16}).*$|^.*$

Demo,,, in which all numbers are matched, but only the numbers satisfying your condition are captured to $1 in format of 15 significant figures.

查看更多
登录 后发表回答