在Java中替换为正则表达式

时间:2015-08-18 06:35:24

标签: java regex

我有一个像(:year)这样的文字我希望提取年份并将其替换为1。 我正在使用

replaceAll("\\:[a-z A-Z]+?($|\\W)", "1");

这给了我答案(1.它删除了结束括号。我应该做什么改变来排除这个结束括号。

输入可能像(:year),:year,:year xxxx,and:year可能在字符串的末尾。在JAVA中使用它

2 个答案:

答案 0 :(得分:4)

output should be: "a2b3a1"

只需使用public class Test { public static void main(String[] args) { String str = "aabbba"; int count = 1; for (int i = 0; i < str.length(); i = i + count) { count = 1; for (int j = i + 1; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) { count = count + 1; } else { System.out.println(str.charAt(i) + "" + count); break; } }//end of inner for }//end of outer for }//end of main }//end of class replaceAll("\\:[a-zA-Z]+\\b", "1"); 。请参阅演示。

https://regex101.com/r/uF4oY4/71

答案 1 :(得分:1)

将第二组视为正面预测。正向前瞻是断言,它不会捕获任何字符,但断言是否可以匹配。

string.replaceAll("\\:[a-z A-Z]+?(?=$|\\W)", "1");