Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to remove what's NOT in regex

Is there an easy way to get the opposite of a regex or do I need to build a new regex that produces the opposite of what I have?

For example, I use this regex to make sure I'm getting proper currency values -- without $ sign.

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

I want to now remove everything that falls outside this pattern. For example, if user enters letters or tries to enter two periods e.g. 7.50.6, I want to remove undesired characters. How do I do that?

like image 470
Sam Avatar asked Oct 30 '22 15:10

Sam


1 Answers

I think you're going at this in the wrong way. First of all, trying to hide input error in such a way is a bad idea. If a user has to type a number and they put an extra dot, what tells you which is the good part and which is the bad? You're better off telling the user there's something wrong with their input.

But typically, you use a regex by specifying what it has to look like AND what are the significant portions you want to keep using capture groups.

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

In case of a phone number, all that matters are the digits, so you can capture them and accept multiple forms of in-between characters. Here's a simple one for a postal code:

([A-Z][0-9][A-Z]) ?([0-9][A-Z][0-9])

Then all you have to do is combine the captured groups. If present, the space won't be captured.

Find more examples on MDN.

like image 141
Domino Avatar answered Nov 15 '22 04:11

Domino