问题
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:
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+$');
来源:https://stackoverflow.com/questions/57374841/how-implement-regex-for-a-textfield-to-allow-one-comma-one-space-at-a-time-in-ex