【问题标题】:extract all substring combinations between 2 characters using regex [duplicate]使用正则表达式提取2个字符之间的所有子字符串组合[重复]
【发布时间】:2016-12-09 17:39:52
【问题描述】:

我收到了String s = "HFGFHFFHSSH"。我想要的输出是'H'之间的所有可能的子字符串组合

上述String的输出应该是HFGFH HFFH HSSH

我尝试了以下方法:

String s = "HFGFHFFHSSH";  
Pattern pattern = Pattern.compile("H(.*?)H");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
  System.out.println(matcher.group(0));
}

不幸的是,输出缺少一个子字符串,导致HFGFH HSSH

【问题讨论】:

标签: java regex string


【解决方案1】:

您应该为此使用前瞻正则表达式并从前瞻内捕获值:

(?=(H[^H]*H))
  • (?=...) 是肯定的前瞻,它断言两边都有 H 包围的文本
  • 前瞻内的(...) 用于捕获组#1 中的匹配值

RegEx Demo

代码:

String s = "HFGFHFFHSSH";  
final Pattern pattern = Pattern.compile("(?=(H[^H]*H))");
Matcher matcher = pattern.matcher(s);

while (matcher.find()) {
   System.out.println(matcher.group(1));
}

【讨论】:

  • regex101 网站让我了解了 regex 的真正情况。 :)
猜你喜欢
  • 2022-11-17
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多