避免在Java中的string.matches()方法中两次匹配相同的值
好吧,我完全重写了这个问题,因为这是有效的,我想知道为什么它有效 假设我有一个值为567的数字testNumber 我想知道接下来的两个数字(shoulldpasstest和shoulldfailtest)是否相同,但在不同的10位 下面是代码:避免在Java中的string.matches()方法中两次匹配相同的值,java,overlapping-matches,Java,Overlapping Matches,好吧,我完全重写了这个问题,因为这是有效的,我想知道为什么它有效 假设我有一个值为567的数字testNumber 我想知道接下来的两个数字(shoulldpasstest和shoulldfailtest)是否相同,但在不同的10位 下面是代码: int testNumber = 567; int num1 = 5; int num2 = 6; int num3 = 7; int shouldPassTest = 756; int shouldFailTest = 777; if(Int
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。这正是我在代码中想要的结果,但我想知道为什么会发生这种情况。matches方法是否测试确保每个数字只匹配一次
谢谢
这篇文章经过高度编辑。运行代码后,我发现该方法完全符合我的要求,但现在我想知道原因。谢谢。我将使用以下方法,因为正则表达式不是解决此问题的好方法:
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;
}
查看实际返回值
从理论上讲,应该失败测试实际上应该通过测试,因为
7如何匹配我的三个标准之一,尽管是3次
但实际情况是,777在测试时返回false。这是
这正是我在代码中想要的结果,但我想知道为什么会这样
发生了。matches方法是否测试以确保每个数字
只匹配一次吗
否,“777”与您指定的图案“[5,6,7][5,6,7][5,6,7]”不匹配
代码中的以下条件将计算为true
if(Integer.toString(shouldFailTest).matches([5,6,7][5,6,7][5,6,7])
听起来你想看看一个数字是否是另一个数字的变码。“不同的解决方案”。使用Integer.toString
后,将字符串分解为字符,并使用数组保存字符。然后可以从数组中删除内容。更好的方法是使用集合
,但如果您的数字可以有多个相同的数字,则这将无法正常工作。但是不要试图用正则表达式来解决这个问题。是的,奇怪的是,代码完全符合我的要求。777返回false。现在我既惊喜又困惑。事实上,777并没有返回false。您正在检查Integer.toString(shouldFailTest).matches(“[5,6,7][5,6,7][5,6,7][5,6,7]”)在上述代码中是否返回true。您摘录的代码甚至不会编译,因为括号在if
语句中不平衡。
System.out.println(Integer.toString(shouldFailTest).matches("[5,6,7][5,6,7][5,6,7]"));