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

问题描述 投票:-1回答:3

我有一个像下面的字符串列表:(没有引号)

"<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>"

我想知道它是否可行?

谢谢

java regex
3个回答
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
投票

试试这个:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.