0

I am very new to regular expression , I needed to get specific value from string contained between ' '

Using regular expression was able to get the values but getting an exception when there is a third ' in between ' '.

Variable rule contains the whole string

IEnumerable<string> possibleValues = Regex
    .Matches(rule, @"'(?<val>.*?)'")
    .Cast<System.Text.RegularExpressions.Match>()
    .Select(match => match.Groups["val"].Value)
    .ToArray();   

When following string is passed

RULE: 'Street Address'
must be 'Samir Complex, 4th Floor, St Andrew's Road, Bandra (West)' (default value)

Expected values was Street Address and Samir Complex, 4th Floor, St Andrew's Road, Bandra (West)

but getting Street Address and Samir Complex, 4th Floor, St Andrew

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Sushant Baweja
  • 202
  • 1
  • 5
  • 14

1 Answers1

6

When matching apostrophes you don't want to match every one: in your case ' within Andrew's should be skipped. You can try checking for word boundary; see details at Difference between \b and \B in regex

@"'(?<val>.*?)'\B"

Code:

string[] possibleValues = Regex
  .Matches(rule, @"'(?<val>.*?)'\B")
  .Cast<Match>()
  .Select(match => match.Groups["val"].Value)
  .ToArray();  
Johnny
  • 8,939
  • 2
  • 28
  • 33
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215