User5590 User5590 - 21 days ago 9
C# Question

Split the string using Regex with the special characters

I have a string as [@variable] -eq 'some value' or 'some value' -eq [@variable] and i want to split it using Regex.

The expected output is as below


  1. [@variable]

  2. -eq

  3. 'some value'



or


  1. 'some value'

  2. -eq

  3. [@variable]



I have the used regular expression \w+|'[\w\s]*' to match and split the string but it gives me below output


  1. variable

  2. eq

  3. some value



which ignores the special characters with the string.

Can anyone please help me on this?

EDIT

The answer by lbrahim is working for most of the scenario but failing when the value is date time.

[@variable] -eq 'MM/dd/yyyy'

The above expression should also work for the same

Answer

Try this:

\[?\@?\-?\w+\]?|\'[\w\s\/]*\'

Demo

Or this:

-\w+|\[\V*\]|\'\V*\'

Demo

Comments