Regex: Lookahead and then lookbehind from the lookahead position

时间:2016-05-18 12:37:16

标签: .net regex

I have a .net regex (and I have to use regex) which currently works by simply matching any non word characters between capture groups (which are capturing test to pass to a method).

In most cases it works fine but in the case where the text to be passed to a method is a negative number the non-word match consumes the minus sign and passes the positive number to the method. To complicate things further the non word characters between capture groups might contain text like " - ", which should be consumed. The text might also be a currency value like " $200" and in this case the "$" should also be consumed.

What I tried was to consume the non word characters until one was followed by a digit, then check if that digit was preceeded by something other than the minus sign and only consume if it was. My regex for this was:

\W+(?!\d(?<![^-]))

however this doesn't seem to work as I expect as this still seems to consume my minus sign, resulting in a positive number being passed to my method.

Is my regex wrong? Or can I not look ahead and then lookbehind from the lookahead position?

How can I get the desired result which is that this text:

" -100"

matches only the whitespace at the beginning. And this text:

" $200"

matches the whitespace and the $ sign.

and this text:

" - 100" 

matches the whitespace, minus sign and following whitespace, but not the number.

An example can be found here

1 个答案:

答案 0 :(得分:1)

似乎你可以使用

\W+(?!(?<=-)\d)

请参阅regexstorm demo

模式说明

  • \W+ - 1个非字字符
  • (?!(?<=-)\d) - 如果1 +非单词字符后跟一个前面有\d的数字-,那么匹配失败的否定前瞻({{1} }})

enter image description here