【问题标题】:Using split method in java to separate different inputs在java中使用split方法来分离不同的输入
【发布时间】:2018-03-13 00:56:31
【问题描述】:

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

【问题讨论】:

  • @stackuser83 考虑到有逗号、空格、空格和括号,我似乎无法将它们分开。我需要能够在一行中添加所有分隔符。

标签: java split


【解决方案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

【讨论】:

    【解决方案2】:

    看起来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];
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2015-04-30
      相关资源
      最近更新 更多