How to check if a string contains a list of characters?

How to check if a list of characters is in a string, for example "ABCDEFGH", how to check if any of them are in a string.

+7
source share
7 answers

use regex in java to test with str.matches(regex_here) regex in java

eg:

  if("asdhAkldffl".matches(".*[ABCDEFGH].*")) { System.out.println("yes"); } 
+18
source

The easiest way to implement this is to use 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> 
+12
source

I think this is a newbie question, so I will give you the easies method that I can think of: using the complex version of indexof includes regex you can try it if you want.

+2
source

From Guava: CharMatcher.matchesAnyOf

 private static final CharMatcher CHARACTERS = CharMatcher.anyOf("ABCDEFGH"); assertTrue(CHARACTERS.matchesAnyOf("39823839A983923")); 
+1
source

This is similar to the homework question ... -_-

You can use the String.contains () function.
For example:

 "string".contains("a"); String str = "wasd"; str.contains("a"); 

but you will need to call it once for each character you want to check.

0
source

Here's how this can be achieved with Pattern and Matcher,

 Pattern p = Pattern.compile("[^A-Za-z0-9 ]"); Matcher m = p.matcher(trString); boolean hasSpecialChars = m.find(); 
0
source

If "ABCDEFGH" is in a string variable, a regex solution is not suitable. This will not work if the string contains any character that has 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 lines asdhAkldffl and ABCDEFGH this fragment outputs:

Does asdhAkldffl contain any of [A, B, C, D, E, F, G, H]? true

0
source

All Articles