Check whether the string contains special characters Kotlin

Advertisements

I need a regex that checks whether a string contains the following characters ‘ " | \ / <> ;

    "Team's<>".contains("/[\"'\\/\\\\<>;|]/;")

    val regex = Regex(pattern = "'.*'.*\".*\\|.*\\\\.*/.*<>", options = setOf(RegexOption.IGNORE_CASE))
    regex.matches(input)

>Solution :

You could include all the characters you’re looking for in a simple character class and escape them.

[\'\"\|\\\/\<\>;]

If the regex finds any match, then the string contains at least one of the characters you’re looking for.

I know you’re coding in Kotlin, but here is an example in Java to show the regex at work.

Pattern pattern = Pattern.compile("[\\'\\\"\\|\\\\\\/\\<\\>;]");

Matcher matcher1 = pattern.matcher("Hello' my \"World\" | This \\ is / <a test>!!;");
if (matcher1.find()) {
    System.out.println("Contains at least one of the characters at: " + matcher1.start());
}

Matcher matcher2 = pattern.matcher("test test test");
if (!matcher2.find()) {
    System.out.println("Does not contain the characters you're looking for");
}

Here is also a link to test the regex

https://regex101.com/r/s2CsFl/1

Leave a ReplyCancel reply