繁体   English   中英

避免在 Java 的 string.matches() 方法中两次匹配相同的值

[英]Avoid matching the same value twice in string.matches() method in Java

好的,我完全重写了这个问题,因为它有效,我想知道它为什么有效。

假设我有一个数字 testNumber,其值为 567。

我想知道接下来的两个数字(shouldPassTest 和 shouldFailTest)是否相同,但在不同的 10 位。

所以这是代码:

int testNumber = 567;
int num1 = 5;
int num2 = 6;
int num3 = 7;

int shouldPassTest = 756; 
int shouldFailTest = 777;


if(Integer.toString(shouldPassTest).matches("[5,6,7][5,6,7][5,6,7]")
{
    //Do some cool stuff
}

if(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]")
    {
        //Do some cool stuff
    }

当您运行它时会发生什么,是从可用数字范围(5、6 和 7)中测试每个数字。 从理论上讲,shouldFailTest实际上应该通过测试,看看 7 如何匹配我的三个标准之一,尽管是 3 次。

但实际情况是 777 在测试时返回 false。 这正是我在代码中想要的结果,但我想知道它为什么会发生。 匹配方法是否测试以确保每个数字只匹配一次?

谢谢!

这篇文章被高度编辑。 运行我的代码后,我发现该方法完全符合我的要求,但现在我想知道为什么。 谢谢。

我会使用以下内容,因为正则表达式不是解决这个问题的好方法:

public class Count {
    private int value;
    public Count() {
        value=0;
    }
    void increment() {
        value++;
    }
    void decrement() {
        value--;
    }

    public int getValue() {
        return value;
    }
}
public static boolean isAnagram(int val1, int val2) {
    Map<Character, Count> characterCountMap=new HashMap<>();
    for(char c:Integer.toString(val1).toCharArray()) {
        Count count=characterCountMap.get(c);
        if(count==null) { count=new Count(); characterCountMap.put(c, count);}
        count.increment();
    }
    for(char c:Integer.toString(val2).toCharArray()) {
        Count count=characterCountMap.get(c);
        if(count==null) { return false; }
        else { count.decrement(); }
        if(count.getValue()==0) {
            characterCountMap.remove(c);
        }
    }
    return characterCountMap.size()==0;
}

请运行:

System.out.println(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"));

查看实际返回值。

从理论上讲,shouldFailTest 实际上应该通过测试,看看 7 如何匹配我的三个标准之一,尽管是 3 次。

但实际情况是 777 在测试时返回 false。 这正是我在代码中想要的结果,但我想知道它为什么会发生。 匹配方法是否测试以确保每个数字只匹配一次?

不,“777”确实匹配您指定的模式“[5,6,7][5,6,7][5,6,7]”

代码中的以下条件将评估为真。

if(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"))

暂无
暂无

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

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