Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a value like this:
hello 'a' 'b' cc '''''

Can anybody help me in finding what regex pattern will return the values enclosed inside single quotes?
Values can be series of single quotes also like*: '<''''>' or '<'''''>'.
HTML



* < and > are used to distinguish between values and enclosing single quotes.
Posted

You can try
C#
string stringToCheck = "'whatever'";
Regex r = new Regex(@"\s'([.]+)'\s", RegexOptions.Compiled);
string s;
foreach (Match m in r.Matches(stringToCheck)) {
   s = m.Groups[0].Value;
   // s should equal whatever
}
 
Share this answer
 
Comments
Shrikant S 25-Mar-15 8:35am    
Thanks for the suggestion Phil, but your answer is not working !

string stringToCheck = "'whatever'";
Regex r = new Regex(@"\s'([.]+)'\s", RegexOptions.Compiled);
string s;
foreach (Match m in r.Matches(stringToCheck))
{
s = m.Groups[0].Value;
// s should equal whatever
MessageBox.Show(s);
}

Its not even returning "whatever" !
phil.o 25-Mar-15 8:38am    
Then debug and see what is the value in m variable.
phil.o 25-Mar-15 14:43pm    
I tested some more regular expressions ; it seems that it does not like the . inside the capture group. The only result I could get is to capture all characters thar are not ' ; so it does not fulfill your requirement:
\s*'([^']+)'\s*.
I don't know how to capture single quotes inside the single quotes.
Matt T Heffron 25-Mar-15 19:55pm    
I think the error was putting the . into the [character_group]
Wouldn't
\s*'(.+)'\s*
capture everything between the outermost ' characters?
phil.o 26-Mar-15 1:36am    
Yes, you're right; just tested it in expresso and that's working.
Good catch, thank you :)
Edit: But it does not pass the test with OP's example, though. It matches only one result, what is enclosed between initial and final single quotes.
The regex:
(?<!')'(.*?)'(?!')
should do it.

According to Expresso:
For:
hello 'a' 'b' cc '''''

it returns 3 matches:
a
b
'''
 
Share this answer
 
Comments
Shrikant S 28-Mar-15 4:02am    
Thanks Matt
After a good rest, found it:
C#
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string str = "hello 'a' 'b' cc '''''";
        Match match = Regex.Match(str, @"(?<=')[^'\s]+(?=')|['](?=')|(?<=')[']");
        while (match.Success)
        {
            Console.WriteLine(match.Value);
            match = match.NextMatch();
        }
    }
}

it will return:
a
b
'
'
'
'
'
 
Share this answer
 
v2
Comments
Shrikant S 28-Mar-15 4:03am    
Thanks Peter, for the solution !!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900