我想要提取两个-分隔符之间的所有数字。
示例:
test-555-2468-123提取的预期结果:
555
2468我尝试使用regex,如下所示:[\d+]+。这至少给了我一个街区的所有数字。但是,我如何添加限制,即数字必须与-字符前和后置?
发布于 2017-05-30 06:54:07
您可以在regex中使用查找器,因为它涉及重叠匹配:
(?<=-)\d+(?=-)在Java代码中:
final Pattern p = Pattern.compile("(?<=-)\\d+(?=-)");(?<=-) -正向后看以断言先前的位置有连字符(?=-) -正向前看以断言下一个位置有连字符发布于 2017-05-30 07:06:51
这是一种使用稍微少一些正则表达式的解决方案,而且(我猜)更简单。
String str = "test-555-2468-123";
// converting the split array into an array list
ArrayList<String> list = new ArrayList<>();
Arrays.stream(str.split("\\-")).forEach(list::add);
// ensure that there must be a "-" before and after by removing the first and last element
list.remove(0);
list.remove(list.size() - 1);
// filter the elements that contains only numbers
list.stream().filter(x -> Pattern.compile("\\d+").matcher(x).matches()).forEach(System.out::println);https://stackoverflow.com/questions/44255352
复制相似问题