简体   繁体   English

在Java中使用split方法分隔不同的输入

[英]Using split method in java to separate different inputs

Using the split method in java to split "Smith, John (111) 123-4567" to "John" "Smith" "111" . 在Java中使用split方法将"Smith, John (111) 123-4567"拆分为"John" "Smith" "111" I need to get rid of the comma and the parentheses. 我需要除去逗号和括号。 This is what I have so far but it doesn't split the strings. 这是我到目前为止的内容,但它不会拆分字符串。

    // 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]);
    }

Can also be solved by using a regular expression to parse the input: 也可以通过使用正则表达式解析输入来解决:

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"));
}

Output: John Smith 111 输出: John Smith 111

It looks like the string.split function does not know to split the parameter value into separate regex match strings. 看起来string.split函数似乎不知道将参数值拆分为单独的正则表达式匹配字符串。

Unless I am unaware of an undocumented feature of the Java string.split() function ( documentation here ), your split function parameter is trying to split the string by the entire value " , \\\\s ( )", which is not literally present in the operand string. 除非我不知道Java string.split()函数的一个未记录的功能( 此处的文档 ),否则您的split函数参数将尝试用整个值“,\\\\ s()”拆分字符串,而该值实际上并不存在。在操作数字符串中。

I am not able to test your code in a Java runtime to answer, but I think you need to split your split operation into individual split operations, something like: 我无法在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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM