Home > Software engineering >  How I can check if a string contains only a few special charterers?
How I can check if a string contains only a few special charterers?

Time:05-04

I want to check only a few special charaters in a string.

For example this "FTO – Gen 3.1 Device - Ref No 11936 - LED" string contains (en-dash)

And I want to remove and replace it with another string if such type of special char appears in the string.

Below special char I want to check if its present the string

\,{,^,},%,`,],>,[,~,<,#,|,

I have listed all of the special char above

Don't know much about regex that how I can get a match only sting contains the above special char.

Your help is much appreciated.

CodePudding user response:

Answer

Try this:

[\\{\^}%`\]>\[~<#|]

Also, check out Regex101

Explanation

The two outermost brackets ([...]) are a character class, which means that anything inside them will match.

Some characters are reserved, and so need to be escaped with a backtick. This is because RegEx uses these characters in its grammar. These characters are: \\, \^, \], and \[ (in this case). The rest just appear in the class as-is.

  • Related