Java正则表达式匹配器在与单个数字组合时不返回连续两位数字的组。

huangapple go评论65阅读模式
英文:

Java Regular Expression Matcher not returning group of 2 consecutive digits when ORing with single digit group

问题

我正在尝试创建一个正则表达式,从字符串中提取所有连续的数字(包括单个数字)。

下面的正则表达式无法提取2个连续的数字。

public static void main(String args[]) {
    print(checkRegex("2G18R"));
}
private static void print(String arr []) {
    for(String s : arr) {
        System.out.println(s);
    }
    System.out.println("----------------------------");
}
private static String [] checkRegex(String str) {
    System.out.println("原始字符串 " + str);
    Pattern pattern = Pattern.compile(".*(\\d{4})|(\\d{3})|(\\d{2})|(\\d+).*");
    Matcher matcher = pattern.matcher(str);
    if(matcher.find()) {
        return new String [] {
            matcher.group(1),
            matcher.group(2),
            matcher.group(3),
            matcher.group(4)
        };
     }
     return new String [] {};
}

预期输出是matcher.group(3)应该返回18。
但它返回null。

总体预期输出是[2, 18]。

英文:

I am trying to create a regular expression that extracts all consecutive digits from a string (including single digit)

Below regular expression is not able to extract 2 consecutive digits.

public static void main(String args[]) {
	print(checkRegex("2G18R"));
}
private static void print(String arr []) {
	for(String s : arr) {
		System.out.println(s);
	}
	System.out.println("-----------------------------");
}
private static String [] checkRegex(String str) {
	System.out.println("original string " + str);
	Pattern pattern = Pattern.compile(".*(\\d{4})|(\\d{3})|(\\d{2})|(\\d+).*");
    Matcher matcher = pattern.matcher(str);
    if(matcher.find()) {
		return new String [] {
			matcher.group(1),
			matcher.group(2),
			matcher.group(3),
			matcher.group(4)
		};
     }
     return new String [] {};
}

Expected output is that matcher.group(3) should return 18.
But it is returning null.

Overall expected output is [2, 18]

答案1

得分: 2

以下是您提供的内容的中文翻译:

原始模式 ".*(\\d{4})|(\\d{3})|(\\d{2})|(\\d+).*" 将匹配类似 "abc1234|567|89|0efg" 的内容。

我想您可能需要这样的模式:"(\\d{1,4})"

public static void main(String[] args) {
    checkRegex("2G18R");
    checkRegex("2G18R15559X9871C1");
}

private static void checkRegex(String str) {
    System.out.println("原始字符串 " + str);
    Pattern pattern = Pattern.compile("(\\d+)");
    Matcher matcher = pattern.matcher(str);
    List<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(matcher.group(1));
    }
    System.out.println("结果: " + result);
}

输出:

原始字符串 2G18R
结果: [2, 18]
原始字符串 2G18R15559X9871C1
结果: [2, 18, 15559, 9871, 1]
英文:

The pattern ".*(\\d{4})|(\\d{3})|(\\d{2})|(\\d+).*" would match something like "abc1234|567|89|0efg"

I suppose you need a pattern like this: "(\\d{1,4})"

public static void main(String[] args) {
    checkRegex("2G18R");
    checkRegex("2G18R15559X9871C1");
}

private static void checkRegex(String str) {
    System.out.println("original string " + str);
    Pattern pattern = Pattern.compile("(\\d+)");
    Matcher matcher = pattern.matcher(str);
    List<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(matcher.group(1));
    }
    System.out.println("Result: " + result);
}

And output:

original string 2G18R
Result: [2, 18]
original string 2G18R15559X9871C1
Result: [2, 18, 15559, 9871, 1]


</details>



# 答案2
**得分**: 1

这里提供的代码演示了如何从包含数字和非数字的字符串数组中提取数字。以下是代码的翻译部分:

```java
// 使用 split 方法分割字符串
String[] array = {
    "2G18R","2sls2l2222l1l1","ksksks2232ksksk2k2k22k222k2k9282"
};

// 在这里,split 方法将字符串根据非数字字符 `\\D+` 进行分割
// 如果所有字符串都以数字开头,那么不需要条件复制,因为它只是复制数组并跳过不以数字开头的字符串
for (String str : array) {
    String[] numbers = str.split("\\D+");
    if (numbers.length > 0 && numbers[0].isBlank()) {
        numbers = Arrays.copyOfRange(numbers, 1, numbers.length);
    }
    System.out.println(Arrays.toString(numbers));
}

// 你还可以使用流的方式过滤出非法字符串
for (String str : array) {
    String[] numbers = Arrays.stream(str.split("\\D+"))
            .filter(s -> !s.isBlank()).toArray(String[]::new);
    System.out.println(Arrays.toString(numbers));
}

这两种方法都会打印出以下结果:

[2, 18]
[2, 2, 2222, 1, 1]
[2232, 2, 2, 22, 222, 2, 9282]

如果你有其他问题或需要进一步帮助,请随时提问。

英文:

It's unclear if you just want the array of numbers or want to use regular expressions. Here is an alternative to matching. Just use split.

String[] array = {
        &quot;2G18R&quot;,&quot;2sls2l2222l1l1&quot;,&quot;ksksks2232ksksk2k2k22k222k2k9282&quot;
};
  • Here, split will split the string on any length of nonDigits \\D+
  • if all your strings start with digits, then you won't need the conditional copy as that just copies the array and skips the first cell if the string doesn't start with a digit.
for (String str : array) {
    String[] numbers = str.split(&quot;\\D+&quot;);
    if (numbers.length &gt; 0 &amp;&amp; numbers[0].isBlank()) {
        numbers = Arrays.copyOfRange(numbers, 1, numbers.length);
    }
    System.out.println(Arrays.toString(numbers));
}

You could also just take a stream approach and filter out the offending string.

for (String str : array) {
    String[] numbers = Arrays.stream(str.split(&quot;\\D+&quot;))
            .filter(s -&gt; !s.isBlank()).toArray(String[]::new);
    System.out.println(Arrays.toString(numbers));
}

both print the following

[2, 18]
[2, 2, 2222, 1, 1]
[2232, 2, 2, 22, 222, 2, 9282]


</details>



huangapple
  • 本文由 发表于 2023年3月7日 23:05:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定