"Hello my name 开发者_C百科is "Joe" and I'm 13."
I want the regex to print out "Joe" only, can this be done?
You didn't provide the platform you're using for this regex but here is one way using php:
$content='Hello my name is "Joe" and I\'m 13.';
preg_match('/"[^"]*"/', $content, $m);
print_r($m);
Update:
As per the comment below here is the code that OP is probably looking for:
$content='foo "Hello my name is "Joe" and I\'m 13." bar';
preg_match('/"[^"]*"([^"]*)"/', $content, $m);
var_dump($m[1]);
OUTPUT
string(3) "Joe"
A regular expression that will find a quoted string within another quoted string:
/\".*?\"(.*)\".*?\"/
http://rubular.com/r/L8dMtNZxP5
The interior quoted string will be in \1.
Now, if you want a more complex nesting structure, you'll need additional logic to account for that. The linked site may help you generate any further logic.
(?<!"[^"]*)"([^"]+)"
Consider this string (with \ escaped quotes): string test = "\"Hello my name is \"Joe\" and I'm 13.\"";
That expression will match "Joe"
and the first capture will be Joe
. I couldn't tell which you were trying to get from your question.
In C#:
var match = Regex.Match(mystring,
"(?<!\"[^\"]*)\"([^\"]+)\"",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
Console.WriteLine(match.Value); // "Joe"
Console.WriteLine(match.Groups[1].Value); // Joe
Here's one fairly generic way to go about finding a single word inside double quotes, using Python's re module.
>>> import re
>>> string = '''"Hello my name is "Joe" and I'm 13"'''
>>> re.compile('"\w+"').search(string)
<_sre.SRE_Match object at 0xb73dc720>
>>> _.group()
'"Joe"'
精彩评论