Java正则表达式替换第一次冒号之前的所有句点

时间:2014-02-26 17:13:05

标签: java regex

示例输入:

this.is:an-example:3.0.3

我需要用正斜杠替换第一个冒号之前的句点,以及用正斜杠替换每个冒号。

需要的输出:

this/is/an-example/3.0.3

3 个答案:

答案 0 :(得分:3)

试试这个:

// sample input
String s1 = "this.is:an-example:3.0.3";

// `s2` contains the desired output
int idx = s1.lastIndexOf(':') + 1;
String s2 = s1.substring(0, idx).replace('.', '/').replace(':', '/') + s1.substring(idx);

// now we test it
System.out.println(s2);
=> this/is/an-example/3.0.3

答案 1 :(得分:2)

String input = "this.is:an-example:3.0.3:";
input = input.replaceAll("^([^:]*)\\.(?=[^:]*:)|:", "$1/");

输出:

this/is/an-example/3.0.3/

答案 2 :(得分:0)

您可以使用此替代品:

String result = yourstr.replaceAll("\\.(?![^:]*$)|:", "/");