2015-04-06 65 views
1

我正在尋找一種優雅的方式來查找一組分隔符之一的第一個外觀。例如,假設我的分隔符集由{";",")","/"}組成。如何獲得indexOf多個分隔符?

如果我的字符串是
"aaa/bbb;ccc)"
我希望得到的結果3("/"的指標,因爲它是第一個出現)。

如果我的字符串是
"aa;bbbb/"
我希望得到的結果2(";"的指標,因爲它是第一個出現)。

等等。

如果字符串不包含任何分隔符,我想返回-1

我知道我可以這樣做,首先找到每個分隔符的索引,然後計算索引的最小值,不考慮-1的。這段代碼變得非常麻煩。我正在尋找一個更短,更通用的方法。

+0

而不是試圖找到每個分隔符一個接一個,這將是更有效地遍歷字符串的字符,測試,如果每個字符是分隔符的一個。或者你可以使用正則表達式。 – 2015-04-06 06:17:07

回答

8

通過正則表達式,它woud就像這樣,

String s = "aa;bbbb/"; 
Matcher m = Pattern.compile("[;/)]").matcher(s); // [;/)] would match a forward slash or semicolon or closing bracket. 
if(m.find())          // if there is a match found, note that it would find only the first match because we used `if` condition not `while` loop. 
{ 
    System.out.println(m.start());     // print the index where the match starts. 

} 
else 
{ 
    System.out.println("-1");      // else print -1 
} 
0

搜索在分隔符的列表,從輸入字符串的每個字符。如果找到,則打印索引。 您也可以使用Set來存儲分隔符

0

下面的程序會給出結果。這是使用RegEx完成的。

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class FindIndexUsingRegex { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    findMatches("aaa/bbb;ccc\\)",";|,|\\)|/"); 
} 

public static void findMatches(String source, String regex) { 
    Pattern pattern = Pattern.compile(regex); 
    Matcher matcher = pattern.matcher(source); 

    while (matcher.find()) { 
     System.out.print("First index: " + matcher.start()+"\n"); 
     System.out.print("Last index: " + matcher.end()+"\n"); 
     System.out.println("Delimiter: " + matcher.group()+"\n"); 
     break; 
    } 
} 

} 

輸出:

First index: 3 
Last index: 4 
Delimiter:/
相關問題