用于解析负数的分隔符

时间:2022-09-22 23:51:56

I want to parse a String using split to find integers (positive and negative). For example, dfgs#&-6d5.,b-dgj895-9-8 would turn into the array [-6, 5, 895, -9, -8].

我想使用split解析一个String来查找整数(正数和负数)。例如,dfgs#& - 6d5。,b-dgj895-9-8将变成数组[-6,5,895,-9,-8]。

In English, the regex would be:

在英语中,正则表达式将是:

  1. Characters that are not digits
  2. 不是数字的字符

  3. Characters that are not dashes followed by digits
  4. 不是破折号的字符后跟数字

  5. Zero-width characters that are followed by a dash that is followed by a digit
  6. 零宽度字符后跟一个后跟数字的破折号

These are the separate components, but I do not know how to join them together:

这些是单独的组件,但我不知道如何将它们连接在一起:

  1. \D+
  2. [^-(?=[0-9])]
  3. (?=-[0-9]+)

2 个解决方案

#1


2  

split is obviously not the appropriate tool to obtain the result you want. However to do it with split you can use this pattern:

拆分显然不是获得所需结果的合适工具。但是,使用拆分可以使用此模式:

String[] nbs = text.split("(?>[^-0-9]+|-(?![0-9]))+|(?=-[0-9])");

But you need to remove empty results after (that can be at the begining or at the end, depending of the string).

但是你需要删除空结果(可以在开头或结尾,取决于字符串)。

#2


2  

It really doesn't sound like split is what you want. Using a Pattern/Matcher seems to be more in line with what you're trying to do:

它真的听起来不像你想要的分裂。使用模式/匹配器似乎更符合您的尝试:

String text = "dfgs#&-6d5.,bdgj895-9-8";

Matcher m = Pattern.compile("-?\\d+").matcher(text);
while (m.find())
    System.out.println(m.group());
-6
5
895
-9
-8

You can use a List<String> to store the matches.

您可以使用List 来存储匹配项。

#1


2  

split is obviously not the appropriate tool to obtain the result you want. However to do it with split you can use this pattern:

拆分显然不是获得所需结果的合适工具。但是,使用拆分可以使用此模式:

String[] nbs = text.split("(?>[^-0-9]+|-(?![0-9]))+|(?=-[0-9])");

But you need to remove empty results after (that can be at the begining or at the end, depending of the string).

但是你需要删除空结果(可以在开头或结尾,取决于字符串)。

#2


2  

It really doesn't sound like split is what you want. Using a Pattern/Matcher seems to be more in line with what you're trying to do:

它真的听起来不像你想要的分裂。使用模式/匹配器似乎更符合您的尝试:

String text = "dfgs#&-6d5.,bdgj895-9-8";

Matcher m = Pattern.compile("-?\\d+").matcher(text);
while (m.find())
    System.out.println(m.group());
-6
5
895
-9
-8

You can use a List<String> to store the matches.

您可以使用List 来存储匹配项。