Java Check a String Contains Any Characters using Apache Commons Lang

Tags: CharSetUtils Apache Commons Apache Commons Lang String

In this Java tutorial we learn how to check a String to identify whether it contains any of given characters using CharSetUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to check a String contains given characters in Java

The Apache Commons Lang library provides the method CharSetUtils.containsAny() to identify whether any of the given characters are present in a specified String value. The following example code shows you how to use the CharSetUtils.containsAny() method in Java.

CheckStringContainsAnyCharacters.java

import org.apache.commons.lang3.CharSetUtils;

public class CheckStringContainsAnyCharacters {
    public static void main(String... args) {
        String stringToCheck = "Simple Solution, Java Tutorials, Apache Commons";

        boolean result1 = CharSetUtils.containsAny(stringToCheck, "x-z");
        boolean result2 = CharSetUtils.containsAny(stringToCheck, "a-c");
        boolean result3 = CharSetUtils.containsAny(stringToCheck, "x", "y", "z");
        boolean result4 = CharSetUtils.containsAny(stringToCheck, "a", "b", "c");
        boolean result5 = CharSetUtils.containsAny(stringToCheck, "xyz");
        boolean result6 = CharSetUtils.containsAny(stringToCheck, "abc");

        System.out.println("Check contains \"x-z\" result: " + result1);
        System.out.println("Check contains \"a-c\" result: " + result2);
        System.out.println("Check contains \"x\", \"y\", \"z\" result: " + result3);
        System.out.println("Check contains \"a\", \"b\", \"c\" result: " + result4);
        System.out.println("Check contains \"xyz\" result: " + result5);
        System.out.println("Check contains \"abc\" result: " + result6);
    }
}
The output is:
Check contains "x-z" result: false
Check contains "a-c" result: true
Check contains "x", "y", "z" result: false
Check contains "a", "b", "c" result: true
Check contains "xyz" result: false
Check contains "abc" result: true

Happy Coding 😊