2013-01-18 197 views
7

如何检查字符列表是否在字符串中,例如“ABCDEFGH”如何检查字符串中是否有任何字符。在Java中如何检查字符串是否包含字符列表?

+0

你的意思是你想检查是否存在字符串包含列表中的字符? –

+0

在问这样的问题之前,可能应该在别处环顾一下。 – sage88

+0

我认为OP意味着询问正则表达式,但不知道如何询问 – Mawia

回答

15

使用正则表达式来检查使用str.matches(regex_here) regex in java

例如:

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

区域设置敏感度如何? – mre

2

我认为这是一个新手的问​​题,所以我会给你easies方法我能想到的: using indexof复杂版本包括regex你可以尝试,如果你想。

0

这似乎是一个家庭作业的问题... -_-

可以使用String.contains()函数。
例如:

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

但你需要为每个要检查每个字符调用一次。

+0

这是一个效率低下的解决方案,使用正则表达式更好。 –

+0

我发布了它,因为如果你还不知道正则表达式,它更简单易懂。 – EAKAE

+0

是的,但如果你想检查它是否只包含数字数据与这种方法是好运气。 – Alex

8

来实现这一点的最彻底的方法是使用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> 
     <groupId>org.apache.commons</groupId> 
     <artifactId>commons-lang3</artifactId> 
     <version>3.5</version> 
    </dependency> 
+0

我收到导入org.apache.commons无法解析 – anon58192932

+2

@advocate可能是因为它没有构建到java中。你必须下载Apache Commons Lang来获取它。 http://commons.apache.org/proper/commons-lang/确保将它添加到你的类路径中。 –

+0

谢谢!对于其他人,你需要解压缩下载包(我建议在你的项目文件夹中)。在Eclipse中右键单击项目 - > Build Path - > Configure Build Path - > Add External Jars - >选择commons lang jars。您的inport语句中还需要正确的版本号:import org.apache.commons.lang3.StringUtils; – anon58192932

1

番石榴:CharMatcher.matchesAnyOf

private static final CharMatcher CHARACTERS = CharMatcher.anyOf("ABCDEFGH"); 
assertTrue(CHARACTERS.matchesAnyOf("39823839A983923")); 
相关问题