2014-10-07 53 views
0

我是新來的正則表達式,所以沒有得到這個。 我需要在Java中匹配兩個String s,其中一個將有x的數量,其他可以在這些地方有任何字符。匹配兩個字符串,一個用x,另一個用任何字符

For example - 
String 1 - this is the time xxxx when i get up 
String 2 - this is the time 0830 when i get up 

這兩個字符串應匹配並返回true。

請建議。

謝謝。

許多人提到這個問題並不是很清楚。我會添加更多的細節 -

1. x can appear 2 to any number of times. 
2. Strings will be dynamic, or in other words, they'll be passed to a method - 

public boolean doesMatch(String str1, String str2) { 
    // matching code 
    return false; 
} 

所以另一個例子是 -

this is xxxday and i xxxx it 
this is friday and i like it 

這兩個字符串也應該匹配。

+0

請澄清你正試圖完成,因爲它不清楚。 – stryba 2014-10-07 12:07:42

回答

2

您需要重建一個狀態引擎:

public boolean doesMatch(String str1, String str2) { 
    if (str1.length() != str2.length()) 
     return false; 
    for (int i = 0; i < str1.length(); i++) 
     if (str1.charAt(i) != 'x' && str1.charAt(i) != str2.charAt(i)) 
      return false; 
    return true; 
} 

這遍歷str1,並確保在str1str2每一個人物都在每個位置相等,除非在str1相應位置是'x'

1
this is the time .{4} when i get up 

這是滿足您的方案

演示這裏的正則表達式:http://regex101.com/r/kO5wP7/1

+0

這也將匹配任何其他字符,但從'x's和數字,但保存。 – Mena 2014-10-07 12:10:07

+0

@Mena當然是。如果你想要它是數字使用'[0-9]'而不是'。' – aelor 2014-10-07 12:14:16

+0

是的,說實話OP的問題不是很清楚,所以你的解決方案可能是最合適的。 – Mena 2014-10-07 12:15:29

1

夠簡單了,因爲你想要麼匹配四x個序列或四個序列的理解數字:

String[] inputs = { 
    "this is the time xxxx when i get up", 
    "this is the time 0830 when i get up" 
}; 
//       | word boundary 
//       | | non-capturing group 
//       | | | 4 digits 
//       | | | | or 
//       | | | || x * 4 
//       | | | || | word boundary 
Pattern p = Pattern.compile("\\b(?:\\d{4}|x{4})\\b"); 
Matcher m; 
// iterating over examples 
for (String s : inputs) { 
    // matching 
    m = p.matcher(s); 
    // iterating over matches 
    while (m.find()) 
     // printing whatever findings 
     System.out.printf("Found \"%s\"!%n", m.group()); 
} 

輸出:

Found "xxxx"! 
Found "0830"! 
1

只需用X代替數字,然後比較

String str1 = "this is the time xxxx when i get up"; 
String str2 = "this is the time 0830 when i get up"; 

if (str2.replaceAll("\\d", "x").equals(str1)) { 
    System.out.println("both are the equal strings"); 
} 

按照您持續更新

簡單地重複第一個字符串的所有字符,如果它不是x則不然比較一下跳過它。

public static boolean doesMatch(String str1, String str2) { 
    if (str1.length() == str2.length()) { 
     for (int i = 0; i < str1.length(); i++) { 
      char ch = str1.charAt(i); 
      // check the character if not x then compare 
      if (ch != 'x' && ch != str2.charAt(i)) { 
       return false; 
      } 
     } 
    } 
    return true; 
} 
+0

無法正常工作,請立即查看更多詳情。根據您的更新, – 2014-10-07 12:49:40

+0

查看更新後的帖子。 – Braj 2014-10-07 13:21:27

相關問題