How do I check if a list of characters are in a String, for example \"ABCDEFGH\" how do I check if any one of those is in a string.
Use Apache Commons StringUtils.containsAny()..satisfies a lot of different use cases one might have for checking if certain characters exist in a string.
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#containsAny-java.lang.CharSequence-char...-
I think this is a newbie question, so i will give you the easies method i can think of: using indexof complex version include regex you can try if you want.
If "ABCDEFGH"
is in a string variable, the regular expression solution is not good. It will not work if the string contains any character that has a special meaning in regular expressions. Instead I suggest:
Set<Character> charsToTestFor = "ABCDEFGH".chars()
.mapToObj(ch -> Character.valueOf((char) ch))
.collect(Collectors.toSet());
String stringToTest = "asdhAkldffl";
boolean anyCharInString = stringToTest.chars()
.anyMatch(ch -> charsToTestFor.contains(Character.valueOf((char) ch)));
System.out.println("Does " + stringToTest + " contain any of " + charsToTestFor + "? " + anyCharInString);
With the strings asdhAkldffl
and ABCDEFGH
this snippet outputs:
Does asdhAkldffl contain any of [A, B, C, D, E, F, G, H]? true
From Guava: CharMatcher.matchesAnyOf
private static final CharMatcher CHARACTERS = CharMatcher.anyOf("ABCDEFGH");
assertTrue(CHARACTERS.matchesAnyOf("39823839A983923"));
The cleanest way to implement this is using StringUtils.containsAny(String, String)
package com.sandbox;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SandboxTest {
@Test
public void testQuestionInput() {
assertTrue(StringUtils.containsAny("39823839A983923", "ABCDEFGH"));
assertTrue(StringUtils.containsAny("A", "ABCDEFGH"));
assertTrue(StringUtils.containsAny("ABCDEFGH", "ABCDEFGH"));
assertTrue(StringUtils.containsAny("AB", "ABCDEFGH"));
assertFalse(StringUtils.containsAny("39823839983923", "ABCDEFGH"));
assertFalse(StringUtils.containsAny("", "ABCDEFGH"));
}
}
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
use regular expression in java to check using str.matches(regex_here)
regex in java
for example:
if("asdhAkldffl".matches(".*[ABCDEFGH].*"))
{
System.out.println("yes");
}