Home > Blockchain >  How to use Regex to extract variable names and values (separated by =) (C#)
How to use Regex to extract variable names and values (separated by =) (C#)

Time:12-28

Why the following regex doesn't work?

(?<name>[^\s] ?)\w?=\w?(?<value>[^\s] ?);

https://regex101.com/r/q7NTdS/1

I have a string:

a = 2.234;
b = Hello;

random text...

c =2;

And I want to extract "a", "b", and "c" (without white spaces) and their values "2.234", "Hello" and "2". What should I change?

CodePudding user response:

\w matches any word character which does not include whitespace. Try using \s which matches any kind of invisible character. (?<name>[^\s] ?)\s?=\s?(?<value>[^\s] ?); - @regex101.

CodePudding user response:

Let's define what name and value are. If

name must start from letter and can contain letters, digits or _

value can contain any symbols but doesn't start or end by white spaces

name and value must be separated by = and optional white spaces.

the whole string must end with ; and white spaces

then pattern can be

\s*(?<name>\p{L}[\p{L}_0-9]*)\s*=\s*(?<value>.*?)\s*;\s*

Fiddle

  • Related