Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check whether the string contains special characters Kotlin

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading