How implement regex for a textfield to allow one c

2019-08-23 11:17发布

I am working on a textfield to make it allow only numbers with max one comma and one space(max) at any occurrence. It can accept value like "5,8", "5 ,8" and "5 , 8". It should not allow two or more spaces or commas at a time.

I have tried below code but its not working.

this.regex = new RegExp('^\\d+(?\s\\d+)?(?:,\\d*(?\s\\d+)?)*$');

1条回答
forever°为你锁心
2楼-- · 2019-08-23 11:30

This is quite a simple solution.

In order to accept possible characters you can use ?, which signifies exactly 0 or exactly 1 occurrence of the preceding character. For your requirement, the regex pattern:

^\d+\s?,\s?\d+$

Will allow 2 numbers (with multiple digits, if you need it) with a comma between them, with optional spaces.

See the example on regex101

To implement in the line of code you shared:

this.regex = new RegExp('^\\d+\\s?,\\s?\\d+$');
查看更多
登录 后发表回答