2012-07-24 41 views
1

我有一個這樣的字符串:1/80% of all goods sold for $44 million dollars or more/90/55 所以基本上我想有模式的字符串:使用Java Pattern和Matcher搜索模式,包括標點符號,如斜線

「一定數量」「斜槓「‘一些文本與任何標點符號,包括斜槓’,‘斜線’,‘一些數量’,‘斜線’,‘一定數量的’

我不能只用在向前的StringTokenizer和記號化斜槓,因爲我的文字塊可能有正斜槓。我對在java中使用模式和匹配器很陌生。有關我如何做到這一點的任何線索?或者可能有用的教程?提前致謝!根據需要

^\d+/.*/\d+/\d+$ 

添加捕獲組:

+0

設計模式?我會重申你的問題。 – davidbuzatto 2012-07-24 15:33:28

+0

因此,分隔符是第一個斜線和最後兩個斜槓,而其他任何斜線都是文本的一部分? – 2012-07-24 15:35:04

+0

Pattern和Mather是Java中的部分或正則表達式(正則表達式)機制。你可以在這裏找到更多信息(http://docs.oracle.com/javase/tutorial/essential/regex/) – Pshemo 2012-07-24 15:39:01

回答

0

也許這會工作作爲一個正則表達式。只要文本不包含換行符,這應該工作。

0

你正在尋找#/#<文本> /#/#

下面是一些代碼應工作:

String toScan = "Did you know that 1/80 of all goods sold for $44 million or more/90/55? It's cool, because 1/5 of all people can type /1/2 like that."; 
    String regexp = "[0-9]{1,}/[0-9]{1,}.{1,}?/[0-9]{1,}/[0-9]{1,}"; 
    Pattern pattern = Pattern.compile(regexp); 
    Matcher m = pattern.matcher(toScan); 
    while(m.find()) 
     System.out.println(m.group()); 
0

這裏是一個簡單的測試

import java.util.regex.*; 

class RTest 
{ 
public static void main(String[] args) 
{ 
    String test1 = "1/80% of all goods sold for $44 million dollars or more/90/55"; 
    String test2 = "1/80% of all goods sold for $44 /million dollars or more/90/55"; 

    String patternStr = "(.*?)/(.*)/(.*?)/(.*?)$"; 
    Pattern pattern = Pattern.compile(patternStr); 

    System.out.println("Test1..."); 
    // Test 1 
    Matcher matcher = pattern.matcher(test1); 
    boolean matchFound = matcher.find(); 

    if (matchFound) 
    { 
     for (int i = 0; i<=matcher.groupCount(); i++) 
     { 
      System.out.println(matcher.group(i)); 
     } 
    } 

    System.out.println("Test2..."); 
    // Test 2 
    matcher = pattern.matcher(test2); 
    matchFound = matcher.find(); 

    if (matchFound) 
    { 
     for (int i = 0; i<=matcher.groupCount(); i++) 
     { 
      System.out.println(matcher.group(i)); 
     } 
    }  
} 

}