【问题标题】:How write regex for matches String and BigInteger in java?java - 如何在java中为匹配String和BigInteger编写正则表达式?
【发布时间】:2020-04-10 10:59:58
【问题描述】:

我尝试使用此网站https://www.freeformatter.com/java-regex-tester.html#ad-output。但我没有成功。

我的 Java 正则表达式:

(.*)\\w+=[0-9][0-9]*$(.*)

要测试的条目:

a = 800000000000000000000000

我的代码需要为data.matches("(.*)\\w+=[0-9][0-9]*$(.*)")a = 800000000000000000000000 提供true

【问题讨论】:

  • 你到底想达到什么目的?
  • @Mureinik 我希望我的程序像 data.matches("(.*)\\w+=[0-9][0-9]*$(.*)") ==真的
  • @Arvind Kumar Avinash 不,它不适用于 .matches()
  • @plaza2009 - 请解释您的real problem,而不仅仅是您尝试的解决方案。

标签: java


【解决方案1】:

按如下方式进行:

public class Main {
    public static void main(String[] args) {
        String[] testStrs = { "a = 800000000000000000000000", "a = ABC800000000000000000000000",
                "a = 800000000000000000000000ABC", "a = 12.45", "a = 800000000000ABC000000000000", "a = ABC",
                "a = 900000000000000000000000", "a = -800000000000000000000000", "a = -900000000000000000000000" };
        for (String str : testStrs) {
            System.out.println(
                    str + " -> " + (str.matches("[A-Za-z]\\s+=\\s+[-]?\\d+") ? " matches." : " does not match."));
        }
    }
}

输出:

a = 800000000000000000000000 ->  matches.
a = ABC800000000000000000000000 ->  does not match.
a = 800000000000000000000000ABC ->  does not match.
a = 12.45 ->  does not match.
a = 800000000000ABC000000000000 ->  does not match.
a = ABC ->  does not match.
a = 900000000000000000000000 ->  matches.
a = -800000000000000000000000 ->  matches.
a = -900000000000000000000000 ->  matches.

说明:

  1. [A-Za-z] 用于字母表
  2. \\s+ 用于空格
  3. [-]? 是可选的 -
  4. \\d+ 用于数字

【讨论】:

  • 不,BigInteger 是任何数字,800000000000000000000000 或 9000000000000000000000000 或其他数字
  • 不,不是。负数呢?正则表达式应该是 "[-]?\\d+"
  • 它需要匹配“a = 800000000000000000000000”
  • 尝试在此站点中重新检查您的正则表达式freeformatter.com/java-regex-tester.html#ad-output
  • it needs to match a = 800000000000000000000000 - 它也应该匹配 a = 900000000000000000000000a = -800000000000000000000000 不是吗?
【解决方案2】:

扩展上一个答案和 atmin 的评论(我还不能在任何地方发布 cmets),您也可以排除前导零:

String regex = "0|(\\-?[1-9]\\d*)";
String stringToTest = "..."
boolean result = stringToTest.matches(regex);

【讨论】:

  • 你是认真的吗?而不是 800000000000000 可以是任何数字
  • 是的,这适用于任何整数(无论多大),但它与前导 0 不匹配(需要 1-9 作为第一个数字)并且没有“-0”,只需采用上一个答案和替换 '=\\s+' 之后的部分;再说一次,这只是一个补充,因为我无法在任何地方发表评论
猜你喜欢
  • 1970-01-01
  • 2011-03-30
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多