我需要用Java編寫一個方法,它可以接受一個String文本參數和一個返回String數組的String「regexes」參數數組。Java String Split/Manipulation
我想返回的數組基本上做什麼String.split
做的,但與多個字符串正則表達式,而不是剝離正則表達式,將其保留在數組中。
例子:
Input: "int a=10; a++;"
Regexes: "int", ";", "++", "="
Output: "int", " a", "=", "10", ";", " a", "++", ";"
我嘗試了一些事情,包括以下內容,但沒有工作
public static String[] splitIntoBits(String in, String[] regex)
{
List<String> bitList = new ArrayList<String>();
for(int i = 0; i < in.length(); i++)
{
int lastIndex=0;
//Check that character against all regexes
for(int j = 0; j < regex.length; j++)
{
if(in.substring(i).startsWith(regex[j]))
{
bitList.add(in.substring(lastIndex, i));
lastIndex=i;
}
}
}
return bitList.toArray(new String[0]);
}
如何處理重疊模式(換句話說,匹配模糊)? – durron597 2013-04-24 21:10:14
您可以在每次拆分後創建一個新的ArrayList,捕獲String []並將它們饋送到列表中。然後使用List將字符串提供給下一個階段。 – 2013-04-24 21:12:45
@ durron597 - 我可能會用更具體的檢查來處理正則表達式之前或之後的內容。 – user2317297 2013-04-24 21:12:57