Giltix
Giltix

Reputation: 33

RegEx: Check for char at the start of string

Some information:

I've got a Delphi XE Regular Expression:

(?<=[*+\/drt><=≥≤≠])\-

Inputstring:

-(2*3)

The RegEx must match a '-' that makes an expression negative. So for example:

-(2*3) //Must Match

But not:

2 - 3 //Must not Match

In the example above, the operator works as a minus, it does not make the whole expression negative.

My solution for this is my regular expression above, it only matches a minus after an operator. It won't match if the char before the minus is an variable, number or some other defined keywords.

My problem

If the minus is at the start of the string, the regular expression does not match, because there is no char in front, even though the character makes the whole expression negative. How can I match this minus, even if it's at the beginning of the string and has no character in front?

Upvotes: 1

Views: 900

Answers (2)

Jer&#244;nimo Zanella
Jer&#244;nimo Zanella

Reputation: 11

Maybe can you try?

(\-\().+(\))

Starts with "-(", any character, followed by ")".

Resulting...

-(2*3) //Must Match
2 - 3 //Must not Match
test -(2*3) //Must Match??
test -( 2*3 ) //Must Match??
test -() //Must not Match??
test -( ) //Must Match??

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

To match either start of string or a char inside the positive character class is

(?<=^|[*+/drt><=≥≤≠])-
    ^^

See the online demo.

However, if you only deal with standalone strings, it is more efficient to convert the positive lookbehind withj a positive character class and an alternative to a negative lookbehind with a negative character class:

(?<![^*+/drt><=≥≤≠])-

See another regex demo. Only test one string after another, not all in a multiline mode.

Note you do not need to escape - outside a character class. No need to escape the / char either, it is not a special regex metacharacter, and you do not need to use it as a regex delimiter in Delphi.

Upvotes: 1

Related Questions