简体   繁体   English

使用正则表达式获取 UNSPSC 中的商品级别

[英]Getting Commodity Level in UNSPSC using Regular Expression

I have got a scenario, where i need to fetch UNSPSC commodity level using regular expression and get level as..我有一个场景,我需要使用正则表达式获取 UNSPSC 商品级别并获取级别为..

each UNSPSC code is of 8 digit ..每个 UNSPSC 代码都是 8 位数字..

Ist Level :XX 00 00 00等级:XX 00 00 00

2nd Level :XX XX 00 00第二层:XX XX 00 00

3rd Level :XX XX XX 00第三层:XX XX XX 00

4th Level :XX XX XX XX.第四层:XX XX XX XX。

Is thery any way to get level using Single Regular Expression, I was using, ((.)+)00 ... for each level match.有什么方法可以使用单个正则表达式获得级别,我使用的是 ((.)+)00 ... 对于每个级别匹配。

Not sure how to do it.不知道该怎么做。 Thanks.谢谢。

Your regex ((.)+)00 matches 1+ times any character followed by 00 which does not take 8 digits into account.您的正则表达式((.)+)00匹配 1+ 次后跟00任何字符,这不考虑 8 位数字。 For the fourth level you want a match that does not end with 00 .对于第四级,您需要不以00结尾的匹配。

If you can not have 4 pairs of 2 times a zero, and 2 times a zero can not occur before not 2 times a zero you might use an alternation with capturing groups.如果您不能有 4 对 2 次零,并且在 2 次零之前不能出现 2 次零,您可以使用捕获组的交替。 Then check in the matcher if group 1, 2 or 3 exists to get level 1, 2 or 3. If there is a match and there is no group, then you will have level 4.然后在匹配器中检查是否存在组 1、2 或 3 以获得级别 1、2 或 3。如果有匹配但没有组,那么您将获得级别 4。

^(?:(0[1-9]|[1-9][0-9])0{6}|(0[1-9]|[1-9][0-9]){2}0{4}|((?:0[1-9]|[1-9][0-9])){3}00|(?:0[1-9]|[1-9][0-9]){4})$

Regex demo正则表达式演示

Explanation解释

  • ^ Start of the string ^字符串的开始
  • (?: Non capturing group (?:非捕获组
    • (0[1-9]|[1-9][0-9])0{6} Match 01-99 followed by 6 times a 0 (0[1-9]|[1-9][0-9])0{6}匹配 01-99 后跟 6 次 0
    • | Or或者
    • (0[1-9]|[1-9][0-9]){2}0{4} Match 2 times 01-99 followed by 4 times a zero (0[1-9]|[1-9][0-9]){2}0{4}匹配 2 次 01-99 后跟 4 次零
    • | Or或者
    • (?:(?:0[1-9]|[1-9][0-9])){3}00 Match 3 times 01-99 followed by 2 times a zero (?:(?:0[1-9]|[1-9][0-9])){3}00匹配 3 次 01-99 后跟 2 次零
    • | Or或者
    • (0[1-9]|[1-9][0-9]){4}) Match 4 times 01-99 (0[1-9]|[1-9][0-9]){4})匹配 4 次 01-99
  • ) Close non capturing group )关闭非捕获组
  • $ End of the string $字符串结尾

For example:例如:

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
        if (null != matcher.group(1)) {
            System.out.println("Level 1");
        } else if (null != matcher.group(2)) {
            System.out.println("Level 2");
        } else if (null != matcher.group(3)) {
            System.out.println("Level 3");
        } else {
            System.out.println("Level 4");
        }   
}

Output:输出:

Full match: 01000000
Level 1
Full match: 10000000
Level 1
Full match: 99990000
Level 2
Full match: 99999900
Level 3
Full match: 55555555
Level 4

Java demo Java 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM