2016-08-11 64 views
0

我試圖捕捉看起來像這樣的線路,例如:無法捕捉單引號中的正則表達式

2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process' 

我使用下面的正則表達式:

\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} \[.*\]\[.*\] Executing Process '.*' 

然而,線沒有被捕獲。我注意到它一直工作到單引號。但如果我添加單引號,則失敗。我認爲可能有兩種不同類型的單引號,但我複製並粘貼了正在使用的引號,但它仍然無效。兩個引號也是由相同的代碼生成的,所以一個單引號應該與另一個引號相同。編輯:
這是正則表達式的代碼。

regexPattern := `\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} \[.*\]\[.*\] Executing Process '.*'` 

log = highlight(log, regexPattern) 
... 
func highlight(log, pattern string) string { 
    regex := regexp.MustCompile(
    matches := regex.FindAllString(log, -1) 

編輯:
我想通了。我得到的日誌是HTML轉義的,所以單引號實際上是&#39。這阻止匹配與單引號

+0

請發表相關的代碼,正如你所說的字符串是動態構建的。 –

+0

@WiktorStribiżew生成日誌消息或正則表達式代碼的代碼? – Josephus

+1

請參閱https://ideone.com/hTE8f9,您的正則表達式匹配輸入字符串。我只是複製/粘貼你的數據。請添加相關的詳細信息,以便我們能夠重現問題。 –

回答

-1

請嘗試這個稍微修改正則表達式。

(\d){4}\/(\d){2}\/(\d){2} (\d){2}:(\d){2}:(\d){2} (\[\w*\]){2} ([\w ])+ '.*' 

我希望它有幫助!如果您有問題,請詢問!

0

嘗試此工作示例代碼(與&#39):

package main 

import "fmt" 
import "regexp" 
import "time" 

var rgx = regexp.MustCompile(`(\d){4}\/(\d){2}\/(\d){2} (\d){2}:(\d){2}:(\d){2} (\[\w*\]){2} ([\w ])+ &#39.*&#39`) 

func main() { 
    s := time.Now().UTC().Format("2006/01/02 15:04:05") + ` [DEV][INFO] Executing Process &#39Some process&#39 ` 
    r := rgx.FindAllString(s, -1) 
    fmt.Println(r) 
} 

輸出:

[2016/08/11 18:13:41 [DEV][INFO] Executing Process &#39Some process&#39] 

嘗試此工作示例代碼(與'):

package main 

import "fmt" 
import "regexp" 
import "time" 

var rgx = regexp.MustCompile(`(\d){4}\/(\d){2}\/(\d){2} (\d){2}:(\d){2}:(\d){2} (\[\w*\]){2} ([\w ])+ '.*'`) 

func main() { 
    s := time.Now().UTC().Format("2006/01/02 15:04:05") + ` [DEV][INFO] Executing Process 'Some process' ` 
    r := rgx.FindAllString(s, -1) 
    fmt.Println(r) // 

    s = `2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process'` 
    r = rgx.FindAllString(s, -1) 
    fmt.Println(r) // 2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process' 
    fmt.Println() 

    s = ` dfgfsdfg sdf gsdf gsdf 2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process' 2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process'` 
    r = rgx.FindAllString(s, -1) 
    fmt.Println(r) // [2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process' 2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process'] 
    fmt.Println() 

    s = `aaaaaaaaaaaaaaaaa asdfsf 'asdfasdf'` 
    r = rgx.FindAllString(s, -1) 
    fmt.Println(r) // [] 
} 

輸出;

[2016/08/11 18:09:01 [DEV][INFO] Executing Process 'Some process'] 
[2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process'] 

[2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process' 2016/07/27 21:37:50 [DEV][INFO] Executing Process 'Some process'] 

[]