2012-05-24 60 views
1

我想要想出一個簡單的正則表達式,它將查找第一個':',然後是未知數的字符串,直到'。'。找到並返回之間的字符串。簡單正則表達式有助於我開始

test example:IWANTTHISBACK. [8909] test 

結果

IWANTTHISBACK 

任何幫助將是一個偉大的

+0

/:(.*?)./ - 我是新來的正則表達式和我有點不確定希望這會幫助我理解。 @Cylian – user101010101

回答

2

試試這個

(?<=:)([^\.]*?)(?=\.) 

說明

<!-- 
(?<=:)([^\.]*?)(?=\.) 

Options: case insensitive 

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=:)» 
    Match the character 「:」 literally «:» 
Match the regular expression below and capture its match into backreference number 1 «([^\.]*?)» 
    Match any character that is NOT a . character «[^\.]*?» 
     Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?» 
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\.)» 
    Match the character 「.」 literally «\.» 
--> 
+0

謝謝你的工作!你能僅選擇第一場比賽嗎? @ Cylian – user101010101

+0

可能或不可能,這取決於你將如何實現它。 – Cylian

3

我想提出一個簡單的正則表達式,將查找 第一:後跟字符串不明數量,直到一個「」「」。被發現 並返回之間的字符串。

你基本上回答了你自己的問題。如果你翻譯這對正則表達式,它看起來相當簡單:

爲先「:」

: 

之後,直到一個不明數量的字符串「」

[^.]* matches all non dots and stops at first dot. 

所以,如果你寫的這一切在一起:

:([^.]*) 

向引用$1將您的字符串。

+0

+1很好解釋。 – Cylian

0

在Java

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Main { 
    public static void main(String[] args) { 
     Pattern pattern = Pattern.compile(":([^.]*)\\."); 
     Matcher matcher = pattern.matcher("test example:IWANTTHISBACK. :abc.[8909] test"); 
     if (matcher.find()) { 
      System.out.println(matcher.group(1)); 
     } 
    } 
} 

輸出:

IWANTTHISBACK