【发布时间】:2015-02-28 17:51:04
【问题描述】:
我想从某些字符串中删除一个字符后跟一个数字 (0-15) 的所有序列。
我不是很喜欢正则表达式,我尽力了,但没有想出解决这个问题的办法。
对于数字序列,我使用了:http://utilitymill.com/utility/Regex_For_Range
表示序列的字符我使用“@”
需要做以下替换:
- @12Test --> 测试(替换@12)
- @0Test --> 测试(替换@0)
- @16Test --> @16Test(@16 没有被替换,只有 0-15)
为了测试正则表达式,我创建了以下 JUnit 测试用例:
public class ReplacementTests {
@Test
public void testNoReplacement1() {
String actual = "Should nothing happen with this String";
String expected = "Should nothing happen with this String";
actual = appendRegexReplacement(actual);
assertEquals(expected, actual);
}
@Test
public void testNoReplacement2() {
String actual = "12Should 5nothing 16happen2 with this13 String";
String expected = "12Should 5nothing 16happen2 with this13 String";
actual = appendRegexReplacement(actual);
assertEquals(expected, actual);
}
@Test
public void testReplacement() {
String actual = "@12There @144are @5some @16which i @15want to @0get rid of!";
String expected = "There @144are some @16which i want to get rid of!";
actual = appendRegexReplacement(actual);
assertEquals(expected, actual);
}
private String appendRegexReplacement(String replacement) {
String regex = "/^@.([0-9]|1[0-5])/";
return replacement.replaceAll(regex, "");
}
}
前两个测试按预期运行。 第三个测试(实际上需要进行替换)结果如下:
- 预期:@144 有一些 @16 我想摆脱它!
- 实际:@12There @144are @5some @16which i @15want to @0get 摆脱!
在此先感谢,感谢您的帮助!
【问题讨论】:
标签: java regex replace expression