2016-12-01 82 views
-3

工作Android上的OCR項目,在一個條件掃描文本格式 出字符串後的從單個字符串中提取傳真號碼或電話號碼?

Tel:+91 345677890 Fax: +91 80 222767000 

中需要提取唯一的電話號碼和傳真號碼。

在第二個例子

[email protected] ,Fax:+91 80 222767000 

我需要在兩個傳真,電話和電子郵件分隔成一個變量

這篇但無法找到解決方案

String cellfound="Tel:+91 345677890 Fax: +91 80 222767000 [email protected]"; 
Pattern cellp1= Pattern.compile(".*\\b(Mobile|M|M)\\b.*",Pattern.CASE_INSENSITIVE); 
Matcher cellm1 = cellp1.matcher(cellnumber); 
if (cellm1.matches()) { 
    cellfound=cellm1.group(); 
    System.out.println("\nbefore cell found "+cellfound); 
    cellfound=cellfound.replaceAll("[^0-9]", " "); 
    System.out.println("\nfinal cell found from pattern :"+cellfound); 
} 
+0

使用String.subString()方法來單獨數據 –

+3

聽起來像是正則表達式的工作。 – Biffen

+0

使用正則表達式作爲電話號碼應該是一個正則表達式。 – Antoniossss

回答

1

這將工作對你而言:

public static void main(String[] args) throws Exception { 
    String s ="Tel:+91 345677890 Fax: +91 80 222767000"; 
    String[] arr = s.split("[a-zA-Z:]+\\s*"); 
    for (String str : arr){ 
     System.out.println(str); 
    } 

    String s2 = "[email protected] ,Fax:+91 80 222767000"; 
    arr = s2.split(",\\w+:"); 
    for (String str : arr){ 
     System.out.println(str); 
    } 
} 

O/P:

<empty String here> // ignore this value 
+91 345677890 
+91 80 222767000 
[email protected] 
+91 80 222767000 
0

你可以試試這個:

(?<=Tel[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)|(?<=Fax[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)|(?<=\\s)(\\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,}\\b) 

說明:

(?<=Tel[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)比賽空間由「電話之前組:「 - >這個捕獲電話號碼。

(?<=Fax[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)匹配空間組由先「傳真」 - >這抓住了傳真號碼

,最後一個(?<=\\s)(\\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,}\\b)是前面有一個空格的電子郵件正則表達式。

正如你所看到的,電話傳真有幾乎相同的正則表達式。我們可以將它合併爲一個,但我想分開它以獲得更清晰的結果。

下面是示例代碼:

import java.util.regex.*; 

public class HelloWorld { 
    public static void main(String []args){ 
     String test = "Tel:+91 345677890 Fax: +91 80 222767000 [email protected]"; 

     String regex = "(?<=Tel[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)|" // this captures the tel number 
       + "(?<=Fax[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)|" // this captures the fax number 
       + "(?<=\\s)(\\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,}\\b)"; // this captures the email string 

     // Remember the CASE_INSENSITIVE option 
     Pattern re = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); 

     Matcher m = re.matcher(test); 
     while (m.find()) { 
      System.out.println(m.group(0).trim()); 
     } 
    } 
} 

預期的結果是這樣的:

+91 345677890                                                      
+91 80 222767000                                                     
[email protected]