2014-09-20 40 views
0

我有一個String的路由項:解析字符串與正則表達式

"key modifier path.to.routing.key;" 
  • "key"是始終存在的(我並不需要存儲這部分)
  • "modifier"(字)可以出現0或更多次(我需要存儲修飾符)
  • "path.to.routing.key"是實際的鍵,並且將始終是該行的最後一個組件,後跟一個「;」可能有0個或更多''。'字符在路由鍵但始終至少1個字(我需要存儲這部分)。

該字符串將在自己的行中與其他非有趣的文本[所以我不能只使用String.split(" ");]。我打算使用regexPattern s到它弄出來使用:

Pattern p = Pattern.compile("...pattern..."); 

進出口新到Java regex,並可能與一些幫助做,

如何使用Pattern到單獨的這個String到它的組件?


,如果有幫助的一些例子:

key public direct routing.key; 
key direct routingkey; 
+0

等等,問題是如何使用正則表達式來查找文件中的行或如何使用正則表達式將行分割成您必須存儲的組件?如果後者 - 爲什麼使用正則表達式? – Fildor 2014-09-20 14:17:51

+1

「該字符串將在其他文件中的其他非有趣的文字自己的行[所以我不能只使用String.split(」「);]」這我覺得矛盾。如果字符串是在它自己的文本行中,爲什麼不能在「」上分割? – Fildor 2014-09-20 14:19:48

+0

@Fildor這兩個,我用正則表達式作爲在文件的其餘部分非有趣的文字可能包含單詞鍵等 – Edd 2014-09-20 14:20:41

回答

3

使用秒。在這裏,我捕捉你的改性劑和鑰匙,看到這樣的正則表達式匹配:

^key (\w+(?: \w+)*) ([\w.]++);$ 
MATCH 1: [Group 1: public direct] [Group 2: routing.key] 
MATCH 2: [Group 1: direct] [Group 2: routingkey] 

這裏是一個regex demo。您可以使用.split(" ")拆分修飾符。


由於代碼:

Pattern pattern = Pattern.compile("^key (\\w+(?: \\w+)*) ([\\w.]++);$", Pattern.MULTILINE); 
Matcher matcher = pattern.matcher("key public direct routing.key;\nkey direct routingkey;"); 
while (matcher.find()) { 
    for (final String modifier : matcher.group(1).split(" ")) 
     System.out.println(modifier); 
    System.out.println(matcher.group(2)); 
} 

這裏是一個online code demo

-1

這裏你想要的一個簡單的示例:

public static void main(String[] args) { 
    Pattern pattern = Pattern.compile("key (?:(.*))?(.*?);"); 
    // key, facultative things (group 1), mandatory thing (group 2) 

    String[] tests = new String[]{"key public direct routing.key;", "key direct routingkey;", "key nomodifier;"}; 

    for (String test : tests) { 
     System.out.println("test: " + test); 

     Matcher matcher = pattern.matcher(test); 
     if (matcher.matches()) { 
      // split facultative modifiers 
      String[] modifiers = matcher.group(1) == null ? new String[0] : matcher.group(1).split(" "); 

      // retrieve the mandatory key 
      String key = matcher.group(2); 

      System.out.println("modifiers: " + Arrays.toString(modifiers) + "; key: " + key); 
     } 
    } 
} 
2

試試這個:

key(?: (.*))? (.+); 

見Debuggex流程圖瞭解它是如何工作的。修飾符將位於組1中,路由鍵將位於組2中。您可以使用MatchResult.group(number))從匹配結果中提取組。

Regular expression visualization

Debuggex Demo