如何在Java中使用正则表达式将“:abc,cde \ t”替换为“,abc | cde”?

时间:2019-03-26 17:15:57

标签: java regex

我有一个字符串列表,如下所示:(不带引号)

"<someother string without :>:abc\t<some other string without \t>"
"<someother string without :>:abc,cde\t<some other string without \t>"
"<someother string without :>:abc,efg,cde\t<some other string without \t>"
"<someother string without :>:abc,cde\t<some other string without \t>"

想将它们转换为:

"<someother string without :>|abc\t<some other string without \t>"
"<someother string without :>|abc|cde\t<some other string without \t>"
"<someother string without :>|abc|efg|cde\t<some other string without \t>"
"<someother string without :>|abc|cde\t<some other string without \t>"

我想知道它是否可行?

谢谢

3 个答案:

答案 0 :(得分:1)

除非您多次应用它,否则不要以为它可以使用正则表达式来实现。您可以改为:

public static String convert(String s) {
    int start = s.indexOf(':') + 1;
    int end = s.indexOf('\t', start);

    return s.substring(0, start)
            + s.substring(start, end).replaceAll(",", "|")
            + s.substring(end, s.length());
}

答案 1 :(得分:1)

尝试这个:

public class T28Regex {
public static void main(String[] args) {
    String[] strings = { "<someother string without *>:abc\t<some other string without \t>",
            "<someother string without *>:abc,cde\t<some other string without \t>",
            "<someother string without *>:abc,efg,cde\t<some other string without \t>",
            "<someother string without *>:abc,cde\t<some other string without \t>" };

    for (String s : strings) {
        System.out.println(s.substring(0, s.indexOf(":")) + "|"
                + s.substring(s.indexOf(":") + 1, s.indexOf("\t", s.indexOf(":"))).replaceAll(",", "|")
                + s.substring(s.indexOf("\t", s.indexOf(":"))));
    }
}
}

答案 2 :(得分:1)

尝试一下

function Replace_(str ) {
  var patt = /(:)((([\w]*(,)?)){2,})(\\t<)/gi;
  var res = str.replace(patt, function($1,$2,$3){
  return $1.replace(/,/g, "|").replace(":", "|");
  });
return res;
}

Check_W3Link