Asha
Asha

Reputation: 4311

Regex to check a string

I'm trying to check a string and then extract all the variables which starts with @. I can't find the appropriate regular expression to check the string. The string may start with @ or " and if it's started with " it should have a matching pair ".

Example 1:

"ip : "+@value1+"."+@value2+"."+@value3+"."+@value4

Example 2:

@nameParameter "@yahoo.com"

Thanks

Upvotes: 0

Views: 481

Answers (3)

user184968
user184968

Reputation:

To check the strings you have provided in your post:

(^("[^"\r\n]"\s+@[\w.]+\s*+?)+)|(((^@[\w.]+)|("@[\w.]+"))\s*)+

Upvotes: 0

Rubens Farias
Rubens Farias

Reputation: 57956

Try this:


string text = "@nameParameter \"@yahoo.com\"";
Regex variables = new Regex(@"(?<!"")@\w+", RegexOptions.Compiled);
foreach (Match match in variables.Matches(text))
{
    Console.WriteLine(match.Value);
}

Upvotes: 0

Adam Luter
Adam Luter

Reputation: 2253

It would probably be easiest to first split the string on each quoted string, then check the unquoted parts for @'s. For example all quoted strings could be: /"[^"]*"/, calling Regex.Split on your string would return an array of strings of the non-quoted parts, which you could then use the expression /@\w+/ to find any @'s.

Upvotes: 1

Related Questions