使用java中的split方法将"Smith, John (111) 123-4567"
拆分为"John"
"Smith"
"111"
。我需要摆脱逗号和括号。这是我到目前为止,但它没有拆分字符串。
// split data into tokens separated by spaces
tokens = data.split(" , \\s ( ) ");
first = tokens[1];
last = tokens[0];
area = tokens[2];
// display the tokens one per line
for(int k = 0; k < tokens.length; k++) {
System.out.print(tokens[1] + " " + tokens[0] + " " + tokens[2]);
}
答案 0 :(得分:1)
也可以使用正则表达式来解析输入:
String inputString = "Smith, John (111) 123-4567";
String regexPattern = "(?<lastName>.*), (?<firstName>.*) \\((?<cityCode>\\d+)\\).*";
Pattern pattern = Pattern.compile(regexPattern);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches()) {
out.printf("%s %s %s", matcher.group("firstName"),
matcher.group("lastName"),
matcher.group("cityCode"));
}
输出:John Smith 111
答案 1 :(得分:0)
看起来string.split
函数不知道将参数值拆分为单独的正则表达式匹配字符串。
除非我不知道Java string.split()函数(documentation here)的未记录的功能,否则你的split函数参数试图将字符串拆分为整个值“,\\ s()” ,字面上不存在于操作数字符串中。
我无法在Java运行时中测试您的代码来回答,但我认为您需要将拆分操作拆分为单独的拆分操作,例如:
data = "Last, First (111) 123-4567";
tokens = data.split(",");
//tokens variable should now have two strings:
//"Last", and "First (111) 123-4567"
last = tokens[0];
tokens = tokens[1].split(" ");
//tokens variable should now have three strings:
//"First", "(111)", and "123-4567"
first = tokens[0];
area = tokens[1];