I have a string " I love A. I hate B ". If I split it by using
string.split("\\p{Punct}")
I will get two strings where string1
will be " I love A " and string2
will be " I hate B ". Please note that in place of " . " I may also have any of the other punctuation characters. How can I recover the exact string as it was before the splitting operation with the correct punctuation character.
保持对字符串的引用 - 如果你有任何一点点,你就无法猜出你以前有过什么
If you split using the following regular expression (using a zero-width look-behind assertion ):
(?<=\p{Punct})
It will not actually consume the punctuation character, but just check that there is a punctuation character directly before the split point. As a result, the punctuation characters are left in the final strings:
String s = "I love A. I hate B.";
String res[] = s.split("(?<=\\p{Punct})");
System.out.println(Arrays.toString(res));
Result:
[I love A., I hate B.]
Now you could concatenate the elements of the array back together to recover the original string.
Demo: http://ideone.com/0umjkZ
You can use StringTokenizer and manage the elements with the method nextElement().
Sample.
String str = "I love A. I hate B";
StringTokenizer st = new StringTokenizer(str,".");
String beforeElement;
String otherElement;
while (st.hasMoreElements()){
beforeElement=st.nextElement();
if(st.hasMoreElements()){
otherElement=st.nextElement();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.