vamsiampolu
vamsiampolu

Reputation: 6622

How to Java Regex to match everything but specified pattern

I am trying to match everything but garbage values in the entire string.The pattern I am trying to use is:

    ^.*(?!\w|\s|-|\.|[@:,]).*$

I have been testing the pattern on regexPlanet and this seems to be matching the entire string.The input string I was using was:

    Vamsi///#k03@g!!!l.com 123**5

How can I get it to only match everything but the pattern,I would like to replace any string that matches with an empty space or a special charecter of my choice.

Upvotes: 1

Views: 13872

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55589

The pattern, as written, is supposed to match the whole string.

^ - start of string.
.* - zero or more of any character.
(?!\w|\s|-|\.|[@:,]) - negative look-ahead for some characters.
.* - zero or more of any character.
$ - end of string.

If you only want to match characters which aren't one of the supplied characters, try simply:

[^-\w\s.@:,]

[^...] is a negated character class, it will match any characters not supplied in the brackets. See this for more information.

Test.

Upvotes: 8

Related Questions