简体   繁体   中英

How do you add a delimiter in a given String format in Java?

I have the following String

"12:00:00, 2:30:003:45:00,23:45:00";

I have to update the string to use the following format:

"12:00:00, 2:30:00 |3:45:00,23:45:00 ";

I am able to split each string, but I do not know how to generate the required format. Here is the code I've written so far:

final String s = "12:00:00, 2:30:003:45:00,23:45:00";

final Pattern p = Pattern.compile("\\s*(\\d+:\\d\\d:\\d\\d)");
final Matcher m = p.matcher(s);
final List<String> tokens = new ArrayList<String>();
while (m.find()) {
    tokens.add(m.group(1));
}
for (String tok : tokens) {
    System.out.printf("[%s]%n", tok);
}

How about this:

final String string = "12:00:00, 2:30:003:45:00,23:45:00";

final Pattern pattern = Pattern.compile("\\s*(\\d+:\\d\\d:\\d\\d)");
final Matcher matcher = pattern.matcher(string);
final List<String> tokens = new ArrayList<String>();
while (matcher.find()) {
    tokens.add(matcher.group(1));
}
System.out.println("tokens = " + tokens);

StringBuilder formattedString = new StringBuilder();
formattedString.append(tokens.get(0));
for (int i = 1; i < tokens.size(); i++) {
    if (i % 2 == 0) {
        formattedString.append(" | ");
    } else {
        formattedString.append(", ");
    }
    formattedString.append(tokens.get(i));
}
System.out.println(formattedString);

Edit: I've updated it to use a for loop when constructing the formatted string based on the comments I've read.

If you want to add | after two dates separated by comma your code can look like

final String s = "12:00:00, 2:30:003:45:00,23:45:00";

final Pattern p = Pattern.compile("(\\d+:\\d\\d:\\d\\d)\\s*,\\s*(\\d+:\\d\\d:\\d\\d)");
final Matcher m = p.matcher(s);
String result = m.replaceAll("$0|");

Or even

String result = s.replaceAll("?:\\d+:\\d\\d:\\d\\d),\\s*(?:\\d+:\\d\\d:\\d\\d)","$0|");

$0 refers to group 0 which holds entire match.

result is 12:00:00, 2:30:00|3:45:00,23:45:00|

You may consider this replaceAll method using lookarounds:

final String s = "12:00:00, 2:30:003:45:00,23:45:00";
System.out.printf("%s%n", s.replaceAll("(?<=:\\d\\d)(?=(?::\\d{1,2}|$))", "|"));

// 12:00|:00, 2:30|:003:45|:00,23:45|:00|

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.

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