Easy way to remove what is NOT in regular expression

Is there a simple way to get the opposite of a regular expression, or do I need to create a new regular expression that creates the opposite of what I have?

For example, I use this regular expression to make sure that I get the correct currency values ​​- without the $ sign.

/^[0-9]+(\.[0-9][0-9]?)?$/ 

I want to remove everything that is beyond the scope of this template. For example, if the user enters letters or tries to enter two periods, for example. 7.50.6, I want to remove unwanted characters. How to do it?

+5
source share
1 answer

I think you are going wrong on this. First of all, trying to hide an input error this way is a bad idea. If the user needs to enter a number and they add an extra dot, which tells you which one is good and which is bad? You better tell the user that something is wrong with their input.

But usually you use a regex to indicate what it should look like. And what are the substantial portions that you want to use with capture groups.

This is a capture group: ([a-z0-9])@example.com ; this is a group without capture: (?:hello|hi) .

In the case of a phone number, all that matters is the numbers, so you can capture them and take several forms between the characters. Here's a simple zip code:

 ([AZ][0-9][AZ]) ?([0-9][AZ][0-9]) 

Then all you have to do is join the captured groups. If they are present, the space will not be recorded.

Find more examples on MDN .

+2
source

Source: https://habr.com/ru/post/1261610/


All Articles