【问题标题】:Is there a way to find special subStrings in this case with regex?在这种情况下,有没有办法用正则表达式找到特殊的子字符串?
【发布时间】:2021-03-29 02:26:16
【问题描述】:

我有一个字符串,在字符串末尾使用正则表达式从中提取数字。

字符串:

'0 DB'!$B$460

子字符串:

460

我解决这个问题如下:

String str = "'0 DB'!$B$460";
String sStr = str.replaceAll(".*?([0-9]+)$", "$1");

老问题链接: Is there a way to find out how many numbers are at the end of a string without knowing the exact index?

现在我有一个不同类型的字符串,我想从中提取某些范围。

字符串:

'0 DB'!$U$305:$AH$376

在这里,我将提取冒号左侧和冒号右侧的某些区域。

美元符号 ($) 之间的区域和它后面的数字。各个区域可以具有不同的长度。第一个美元符号之前的部分可以由字母和数字组成

所以这将是 4 个子字符串。

子字符串:

1: 上

2:305

3:啊

4:376

我也在考虑用正则表达式解决这个问题。但不幸的是,我在这方面的知识有限。

有没有人知道如何使用正则表达式解决这个问题?还是有其他方法?

谢谢

【问题讨论】:

标签: java regex string substring


【解决方案1】:

另一种选择是使用特定模式将 4 个部分作为捕获组。

^.*?([A-Z])\$(\d+):\$([A-Z]+)\$(\d+)$

说明

  • ^ 字符串开始
  • .*? 以非贪婪的方式匹配除换行符以外的任何字符 0 次以上
  • ([A-Z])\$ 在第 1 组中捕获一个字符 A-Z 并匹配 $
  • (\d+):\$ 捕获 1+ 数字组 2 并匹配 :$
  • ([A-Z]+)\$ 在第 1 组中捕获 1+ 个字符 A-Z 并匹配 $
  • (\d+) 匹配第 4 组中的 1+ 个数字
  • $ 字符串结束

Regex demo | Java demo

示例代码

String regex = "^.*?([A-Z])\\$(\\d+):\\$([A-Z]+)\\$(\\d+)$";
String string = "'0 DB'!$U$305:$AH$376";

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println(matcher.group(i));
    }
}

要同时匹配两个示例字符串,您可以将第二部分设为可选。

^.*?([A-Z])\$(\d+)(?::\$([A-Z]+)\$(\d+))?$

查看另一个regex demo

【讨论】:

    【解决方案2】:

    对于这个要求,您可以简单地使用正则表达式 (?&lt;=\\$)\\w+,这意味着 one or more 单词字符 preceded by $

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            String str = "'0 DB'!$U$305:$AH$376";
            Matcher matcher = Pattern.compile("(?<=\\$)\\w+").matcher(str);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
    

    输出:

    U
    305
    AH
    376
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多