Check Whether a String Contains Only Special Characters

How to find if a string contains "ONLY" Special characters in java

You can use:

String splChrs = "-/@#$%^&_+=()" ;
boolean found = inputString.matches("[" + splChrs + "]+");

PS: I have rearranged your characters in splChrs variable to make sure hyphen is at starting to avoid escaping. I also removed a redundant (and problematic) hyphen from middle of the string which would otherwise give different meaning to character class (denoted range).

Thanks to @AlanMoore for this note about character in character class:

^ if it's listed first; ] if it's not listed first; [ anywhere; and & if it's followed immediately by another &.

Check whether a string contains only special characters

Match where the string has only characters, that are not in the class defined here as a-z, A-Z or 0-9.

var regex = /^[^a-zA-Z0-9]+$/

Test it...

console.log( "My string to test".match(regex) )
console.log( "My string, to test!".match(regex) )

How can I check if a string contains only a particular set of special characters in Javascript?

I want to check if a string contains anything other than following special characters ~!@#$

You can try below regex

^[^~!@#$]+$

Pattern explanation:

  ^                        the beginning of the line
[^~!@#$]+ any character except:
'~', '!', '@', '#', '$'
(1 or more times )
$ the end of the line

Learn more... about character sets

enter image description here

Trying to check if string contains special characters or lowercase java

matches will try matching from start of string.If at the start there is not lowercase or Special characters it will fail.Use .find or simply make positive assertion.

^[A-Z0-9]+$

If this passes with matches its a valid string for you.

How to check if string contains only specific characters

You are forgetting that you have space too in your string. Try replacing your function with this,

function checkString(string $string) {
if (preg_match('/^[a-zA-Z0-9.\/:, ]+$/', $string)) {
var_dump('yes');
} else {
var_dump('no');// return no
}
}

How to check if a string contains only [numbers OR special characters] in python

You can use a regular expression to check whether a string contains only digits, hyphens or slashes.

>>> bool(re.match('[\d/-]+$', '2015-07-01'))
True
>>> bool(re.match('[\d/-]+$', '2015-Jul-01'))
False

We don't need the ^ anchor here because match starts from the beginning of the string.

Alternatively, with all and without a regex:

>>> from string import digits
>>> allowed = set(digits).union('/-')
>>> all(c in allowed for c in '2015-07-01')
True
>>> all(c in allowed for c in '2015-Jul-01')
False


Related Topics



Leave a reply



Submit