[英]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.