Java String Split with multiple delimiter using pipe '
I am trying to break a string b = "x+yi" into a two integers x and y.
This is my original answer. Here I removed trailing 'i' character with substring method:
int Integerpart = (int)(new Integer(b.split("+")[0]));
int Imaginary = (int)(new Integer((b.split("+")[1]).
substring(0, b.split("+")[1].length() - 1)));
But I found that the code below just works same:
int x = (int)(new Integer(a.split("+|i")[0]));
int y = (int)(new Integer(a.split("+|i")[1]));
Is there something special with '|'? I looked up documentation and many other questions but I couldn't find the answer.
You can use the given link for understanding of How Delimiters Works .
How do I use a delimiter in Java Scanner?
Another alternative Way
You can use useDelimiter(String pattern) method of Scanner class. The use of useDelimiter(String pattern) method of Scanner class. Basically we have used the String semicolon(;) to tokenize the String declared on the constructor of Scanner object.
There are three possible token on the String “Anne Mills/Female/18″ which is name,gender and age. The scanner class is used to split the String and output the tokens in the console.
import java.util.Scanner;
/*
* This is a java example source code that shows how to use useDelimiter(String pattern)
* method of Scanner class. We use the string ; as delimiter
* to use in tokenizing a String input declared in Scanner constructor
*/
public class ScannerUseDelimiterDemo {
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the delimiter used
System.out.println("The delimiter use is "+scan.delimiter());
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
}
The split() method takes a regular expression that controls the split. Try "[+i]". The braces mark a group of characters, in this case "+" and "i".
However, that won't accomplish what you are trying to do. You will end up with something "b = x", "y", "". Regular expressions also offer search and capture capabilities. Look at String.matches(String regex).
链接地址: http://www.djcxy.com/p/78352.html上一篇: 从字符串中提取字符和单词
下一篇: Java字符串使用管道分割多个分隔符'