[英]How can I split a string in Java and retain the delimiters?
I have this string (Java 1.5): 我有这个字符串(Java 1.5):
:alpha;beta:gamma;delta
I need to get an array: 我需要一个数组:
{":alpha", ";beta", ":gamma", ";delta"}
What is the most convenient way to do it in Java? 在Java中最方便的方法是什么?
str.split("(?=[:;])")
This will give you the desired array, only with an empty first item. 这将为您提供所需的数组,仅使用空的第一项。 And:
和:
str.split("(?=\\b[:;])")
This will give the array without the empty first item. 这将给阵列没有空的第一项。
(?=X)
which is a zero-width positive lookahead (non-capturing construct) (see regex pattern docs ). (?=X)
,这是一个零宽度的正向前瞻(非捕获构造)(参见正则表达式模式文档 )。 [:;]
means "either ; or :" [:;]
表示“要么;或者”: \\b
is word-boundary - it's there in order not to consider the first :
as delimiter (since it is the beginning of the sequence) \\b
是字边界 - 它是为了不考虑第一个:
作为分隔符(因为它是序列的开头) To keep the separators, you can use a StringTokenizer : 要保留分隔符,可以使用StringTokenizer :
new StringTokenizer(":alpha;beta:gamma;delta", ":;", true)
That would yield the separators as tokens. 这会使分隔符成为标记。
To have them as part of your tokens, you could use String#split
with lookahead . 要将它们作为令牌的一部分,您可以使用
String#split
with lookahead 。
/**
* @param list an empty String list. used for internal purpose.
* @param str String which has to be processed.
* @return Splited String Array with delimiters.
*/
public String[] split(ArrayList<String> list, String str){
for(int i = str.length()-1 ; i >=0 ; i--){
if(!Character.isLetterOrDigit((str.charAt(i)))) {
list.add(str.substring(i, str.length()));
split(list,str.substring(0,i));
break;
}
}
return list.toArray(new String[list.size()]);
}
You can do this by simply using patterns and matcher class in java regx. 您可以通过在java regx中使用模式和匹配器类来完成此操作。
public static String[] mysplit(String text)
{
List<String> s = new ArrayList<String>();
Matcher m = Pattern.compile("(:|;)\\w+").matcher(text);
while(m.find()) {
s.add(m.group());
}
return s.toArray(new String[s.size()]);
}
This should work with Java 1.5 (Pattern.quote was introduced in Java 1.5). 这应该适用于Java 1.5(在Java 1.5中引入了Pattern.quote)。
// Split the string on delimiter, but don't delete the delimiter
private String[] splitStringOnDelimiter(String text, String delimiter, String safeSequence){
// A temporary delimiter must be added as Java split method deletes the delimiter
// for safeSequence use something that doesn't occur in your texts
text=text.replaceAll(Pattern.quote(delimiter), safeSequence+delimiter);
return text.split(Pattern.quote(safeSequence));
}
If first element is the problem: 如果第一个元素是问题:
private String[] splitStringOnDelimiter(String text, String delimiter, String safeSequence){
text=text.replaceAll(Pattern.quote(delimiter), safeSequence+delimiter);
String[] tempArray = text.split(Pattern.quote(safeSequence));
String[] returnArray = new String[tempArray.length-1];
System.arraycopy(tempArray, 1, returnArray, 0, returnArray.length);
return returnArray;
}
Eg, here "a" is the delimiter: 例如,这里“a”是分隔符:
splitStringOnDelimiter("-asd-asd-g----10-9asdas jadd", "a", "<>")
You get this: 你得到这个:
1.: -
2.: asd-
3.: asd-g----10-9
4.: asd
5.: as j
6.: add
If you in fact want this: 如果你其实想要这个:
1.: -a
2.: sd-a
3.: sd-g----10-9a
4.: sda
5.: s ja
6.: dd
You switch: 你切换:
safeSequence+delimiter
with 同
delimiter+safeSequence
Assuming that you only have a finite set of seperators before the words in your string (eg ;, : etc) you can use the following technique. 假设在字符串中的单词之前只有一组有限的分隔符(例如;,:等),您可以使用以下技术。 (apologies for any syntax errors, but its been a while since I used Java)
(对于任何语法错误道歉,但自从我使用Java以来已经有一段时间了)
String toSplit = ":alpha;beta:gamma;delta "
toSplit = toSplit.replace(":", "~:")
toSplit = toSplit.replace(";", "~;")
//repeat for all you possible seperators
String[] splitStrings = toSplit.split("~")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.