2

我有以下字符串:

"\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"

如果我使用相同的表达式来解析设备类型,我会得到以下结果:

"         ces DEVICETYPE \nSometext"

找到 \n 时,如何让我的正则表达式停止?

4

3 回答 3

2

In .NET you can use RegexOptions.Multiline. This changes the behaviour of ^ and $.
Rather than meaning the start and end of your string, they now mean start and end of any line within your string.

Regex r = new Regex(@"(?<=\bProduct:).+$", RegexOptions.Multiline);
于 2012-11-22T10:37:25.973 回答
2

也许这个?

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

如果您想要的只是 ces 之后和 \n 之前的内容,那就是..

于 2012-11-22T10:22:40.887 回答
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»
于 2012-11-22T10:20:01.050 回答