2017-05-30 92 views
1

我想提取之间的所有数字两个-分隔符。如何仅提取分隔符之间的数字?

实施例:

test-555-2468-123 

期望的结果来提取:

555 
2468 

我尝试使用正则表达式如下:[\d+]+。这至少给我一个块中的所有数字。但是,我怎样才能添加限制,该数字必须在-字符的前后加上后缀?

+3

使用' - (\ d +) - '并从第一个捕获组中提取值。 – Tushar

+0

这只会给我'555'。但我需要所有的团体。 – membersound

+0

使用'while(matcher.find())'检索所有组 –

回答

9

,因为它涉及重叠匹配您可以使用您正则表达式lookarounds:

(?<=-)\d+(?=-) 

在Java代码:

final Pattern p = Pattern.compile("(?<=-)\\d+(?=-)"); 

RegEx Demo

  • (?<=-) - 正回顾后发断言,以前位置有一个连字符
  • (?=-) - 正预测先行断言,下一个位置有一个连字符
+0

有关在java中使用正则表达式和lookaround的好消息吗? –

+1

对于环视阅读:http://www.regular-expressions.info/lookaround.html否则http://www.regular-expressions.info/有很多好东西,学习正则表达式 – anubhava

+1

非常感谢你! :) –

0

这是使用少一点正则表达式的解决方案和(我猜的)更直接。

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); 
+1

为什么我应该事先分割正则表达式模式匹配器吗? – membersound

+0

我只是认为这是一个更直接的解决方案,使用split来确保'='存在于双方。我总是发现正则表达式的可读性较差。 @membersound – Sweeper

相关问题