2012-11-22 23 views
2

我有以下字符串:讓正則表達式別老盯着 n

"\t Product:   ces DEVICE TYPE \nSometext" //between ":" and "ces" are 9 white spaces 

我需要解析的部分「設備類型」。我試圖用正則表達式來做到這一點。我用這個表達式,它工作。

((?<=\bProduct:)(\W+\w+){3}\b) 

這個表達式返回:

"   ces DEVICE TYPE" 

的問題是在這裏:有些設備有一個像這樣的字符串:

"\t Product:   ces DEVICETYPE \nSometext" 

如果我用同樣的表達解析裝置I型得到這個結果:

"   ces DEVICETYPE \nSometext" 

如何在找到\ n時停止正則表達式?

回答

2

也許這?

(?<=ces)[^\\n]+ 

如果你想要的是CES後\ n表示是之前有什麼..

+0

由於該做的: )多餘的\使它的工作! – 2pietjuh2

1

你可以使用:

(?m)((?<=\bProduct:).+) 

說明:

(?m)((?<=\bProduct:).+) 

Match the remainder of the regex with the options:^and $ match at line breaks (m) «(?m)» 
Match the regular expression below and capture its match into backreference number 1 «((?<=\bProduct:).+)» 
    Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\bProduct:)» 
     Assert position at a word boundary «\b» 
     Match the characters 「Product:」 literally «Product:» 
    Match any single character that is not a line break character «.+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 


or 

    ((?<=\bProduct:)[^\r\n]+) 

說明

((?<=\bProduct:)[^\r\n]+) 

Match the regular expression below and capture its match into backreference number 1 «((?<=\bProduct:)[^\r\n]+)» 
    Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\bProduct:)» 
     Assert position at a word boundary «\b» 
     Match the characters 「Product:」 literally «Product:» 
    Match a single character NOT present in the list below «[^\r\n]+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
     A carriage return character «\r» 
     A line feed character «\n» 
+0

感謝明確的答案:)如果你改變[^ \ r \ n]至第二正則表達式的工作原理[^ \\ \\ [R n]或[^ \\ n]的 – 2pietjuh2

2

在.NET中你可以使用RegexOptions.Multiline。這改變了^$的行爲。
而不是意味着你的字符串的開始和結束,他們現在意味着你的字符串中任何行的開始和結束。

Regex r = new Regex(@"(?<=\bProduct:).+$", RegexOptions.Multiline);