我有以下字符串:
"\t Product: ces DEVICE TYPE \nSometext" //between ":" and "ces" are 9 white spaces
我需要解析“DEVICE TYPE”部分。我正试图用正则表达式做到这一点。我使用这个有效的表达式。
((?<=\bProduct:)(\W+\w+){3}\b)
此表达式返回:
" ces DEVICE TYPE"
问题出在这里:有些设备有这样的字符串:
"\t Product: ces DEVICETYPE \nSometext"
如果我使用相同的表达式来解析设备类型,我得到结果:
" ces DEVICETYPE \nSometext"
如果找到\ n,如何让我的正则表达式停止?
答案 0 :(得分:2)
也许这个?
(?<=ces)[^\\n]+
如果你想要的只是在ces之后和之前的那个......那就是..
答案 1 :(得分:2)
在.NET中,您可以使用RegexOptions.Multiline
。这会更改^
和$
的行为
它们不是指字符串的开头和结尾,而是指字符串中任何一行的开头和结尾。
Regex r = new Regex(@"(?<=\bProduct:).+$", RegexOptions.Multiline);
答案 2 :(得分: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»