2013-01-18 194 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")); 
相關問題