【问题标题】:Regex number range正则表达式数字范围
【发布时间】:2019-09-10 13:47:21
【问题描述】:

我正在使用 BeanIO 框架来解析文件。在我的 XML 代码中,我想要 一个 3 位字段,仅包含特定范围的数字,从 000 到 199。

我尝试了以下方法(该字段必须作为字符串操作):

<field name="recordType" length="3" minOccurs = "0" regex = "[0-1][0-9][0-9]"/>

它似乎不起作用。 有什么想法吗?

提前致谢!

【问题讨论】:

  • 尝试删除不必要的空格。
  • 你可能需要锚点^[0-1][0-9][0-9]$ 否则1999 是有效的。
  • 不,还是不行。
  • 我明白了,请参阅 BeanIO 文档。
  • 请发布不匹配的示例文件。我认为此时举个具体的例子可能会有所帮助。

标签: java regex xml bean-io


【解决方案1】:

我的猜测是,也许您可​​能想要设计一个表达式来覆盖除三位数之外的其他单位数和双位数,例如:

^([0-1][0-9]{2}|[0-9]{2}|[0-9])$

或者,

^([0-1][0-9]{2}|[0-9]{1,2})$

或者,

^(?:[0-1][0-9]{2}|[0-9]{1,2})$

Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{

    public static void main(String[] args){

        final String regex = "^(?:[0-1][0-9]{2}|[0-9]{2}|[0-9])$";
        final String string = "0\n"
             + "1\n"
             + "2\n"
             + "00\n"
             + "11\n"
             + "22\n"
             + "99\n"
             + "100\n"
             + "000\n"
             + "199\n"
             + "200";

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

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

输出

Full match: 0
Full match: 1
Full match: 2
Full match: 00
Full match: 11
Full match: 22
Full match: 99
Full match: 100
Full match: 000
Full match: 199

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多