I'm trying to separate the tokens on a string expression. The expression looks like this:

-1-2+-3

This is the regex I'm using:

[\d\.]+|[-][\d\.]+|\+|\-|\*|\/|\^|\(|\)

This brings me these matches:

-1
-2
+
-3

I was expecting:

-1
-
2
+
-3

Any ideas how can I distinct negative numbers from operators?

有帮助吗?

解决方案

Maybe you could try this one; it makes use of a look-behind:

((?<=\d)[+*\/^()-]|\-?[\d.]+)

I tested it here.

Basically, makes sure that there is a number before the operator to decide what to match. So, if there is a digit before the operator, treat the operator alone, otherwise, combine the minus with the digit.

EDIT: Separated the brackets from the lot, just in case (demo):

((?<=\d)[+*\/^-]|[()]|\-?[\d.]+)

其他提示

This pattern should do what you're looking for:

^(?:(?<num>-?[\d\.]+)(?:(?<op>[-+*/^])|$))+$

For example:

var input = "-1-2+-3";
var pattern = @"^(?:(?<num>-?[\d\.]+)(?:(?<op>[-+*/^])|$))+$";
var match = Regex.Match(input, pattern);
var results =
    from Group g in match.Groups.Cast<Group>().Skip(1)
    from Capture c in g.Captures
    orderby c.Index
    select c.Value;

Will produce:

-1 
- 
2 
+ 
-3 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top