0

I have a requirement to remove all the characters which are not matching to a given regex expression. I know we can invert the regex using ^. But in my case the regex expression varies for each input. I am trying to achieve a generic solution. Is there any way, we can invert any dynamic regex expression ? or any other option to remove non matching characters ?

The following snippet gives an idea, what I am trying to achieve.

$(document).ready(function(){
  $('input[check]').on('input',(function(){  
    //validate the input value with regex and remove none matching charectors
  }))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="string" check='(\d|[a-z])'/>
Jithu Rajan
  • 452
  • 3
  • 14

1 Answers1

0

Is this what you're looking for? How to negate the whole regex?

For example, if you were looking for:

[abc]{3}

Which would match cab but not dad, obviously you cannot just say:

[^abc]{3}    # Does not work!

Since that would not match cab or dad.

Instead, you could do something like this:

^(?![abc]{3})

Example: https://regex101.com/r/CvvPt0/2 for no capture (my example).
Example 2: https://regex101.com/r/CvvPt0/3 to capture 3 characters too.

Note that I don't know how you want to implement it, but I can modify it a little if you share with us.

Community
  • 1
  • 1
Addison
  • 7,322
  • 2
  • 39
  • 55