2013-04-11 53 views
0

我有格式的字符串:將字符串分割的Java

< 923451234567>:嗨,這裏是文本。

現在我想要得到的手機號碼(沒有任何非字母數字字符),即923451234567在>符號串之間<的開始,也是文本即嗨這裏是文本。

現在我可以放置一個硬編碼邏輯,我目前正在這樣做。

String stringReceivedInSms="<+923451234567>: Hi here is the text."; 

String[] splitted = cpaMessage.getText().split(">: ", 2); 
String mobileNumber=MyUtils.removeNonDigitCharacters(splitted[0]); 
String text=splitted[1]; 

如何從正則表達式的字符串中整齊地獲取所需的字符串?這樣,只要字符串的格式發生變化,我就不必更改代碼。

回答

3
String stringReceivedInSms="<+923451234567>: Hi here is the text."; 

Pattern pattern = Pattern.compile("<\\+?([0-9]+)>: (.*)"); 
Matcher matcher = pattern.matcher(stringReceivedInSms); 
if(matcher.matches()) { 
    String phoneNumber = matcher.group(1); 
    String messageText = matcher.group(2); 
} 
+0

謝謝你,先生......這就是工作的偉大 – 2013-04-11 10:25:40

+0

如果'%23'有時也會出現,而不是開始'<',怎麼會爲正則表達式的變化? – 2013-04-16 11:11:23

+0

'%23'編碼爲'#',可能需要先解碼。沒有解碼,這就是你要找的東西:'(?:<|%23)\\ +?([0-9] +)>:(。*)'。 – pfyod 2013-04-16 11:16:07

2

使用該模式相匹配的正則表達式 - <\\+?(\\d+)>: (.*)

使用PatternMatcher Java類來匹配輸入字符串。

Pattern p = Pattern.compile("<\\+?(\\d+)>: (.*)"); 
Matcher m = p.matcher("<+923451234567>: Hi here is the text."); 
if(m.matches()) 
{ 
    System.out.println(m.group(1)); 
    System.out.println(m.group(2)); 
} 
0

您可以通過只是在做您的手機號碼:

stringReceivedInSms.substring(stringReceivedInSms.indexOf("<+") + 2, stringReceivedInSms.indexOf(">")) 

那麼試試這個片斷:

public static void main(String[] args){ 
     String stringReceivedInSms="<+923451234567>: Hi here is the text."; 

     System.out.println(stringReceivedInSms.substring(stringReceivedInSms.indexOf("<+") + 2, stringReceivedInSms.indexOf(">"))); 
    } 

你並不需要分割的字符串。

2

您需要使用正則表達式,以下模式將工作:

^<\\+?(\\d++)>:\\s*+(.++)$ 

這裏是你將如何使用它 -

public static void main(String[] args) throws IOException { 
    final String s = "<+923451234567>: Hi here is the text."; 
    final Pattern pattern = Pattern.compile("" 
      + "#start of line anchor\n" 
      + "^\n" 
      + "#literal <\n" 
      + "<\n" 
      + "#an optional +\n" 
      + "\\+?\n" 
      + "#match and grab at least one digit\n" 
      + "(\\d++)\n" 
      + "#literal >:\n" 
      + ">:\n" 
      + "#any amount of whitespace\n" 
      + "\\s*+\n" 
      + "#match and grap the rest of the string\n" 
      + "(.++)\n" 
      + "#end anchor\n" 
      + "$", Pattern.COMMENTS); 
    final Matcher matcher = pattern.matcher(s); 
    if (matcher.matches()) { 
     System.out.println(matcher.group(1)); 
     System.out.println(matcher.group(2)); 
    } 
} 

我已經加入了Pattern.COMMENTS標誌,從而代碼將與嵌入的評論一起工作以供將來參考。

輸出:

923451234567 
Hi here is the text.