How to use regex in a c#, specifically getting the data inside a double quote?
For example, we just want to get the data inside double quotes from a list of strings:
String result = strin开发者_运维技巧g.Empty;
List<string> strings = new List<string>();
strings.add("string=\"string\"");
strings.add("stringwithspace=\"string with space\"");
strings.add("untrimmedstring=\" untrimmed string\"");
strings.add("anotheruntrimmedstring=\"here it is \"");
strings.add("number=\"13\"");
strings.add("blank=\"\"");
strings.add("whitespace=\" \"");
StringBuilder z = new StringBuilder();
foreach(string x in strings){
if(x has a string inside the doublequote){ //do the regex here
z.append(x + "\n");
}
}
and the result would be:
string="string"
stringwithspace="string with space" untrimmedstring="untrimmed string" anotheruntrimmedstring="here it is" number="13"Any way we could do this?
Or are there some other easier and more optimized ways than using regex?
Thanks a lot.
If the string inside the double quotes are guaranteed not to have a double quotes character, you can use the following regex to capture the trimmed string inside the double quotes.
^(\w+)="\s*([^"]+)\s*"$
$2
or matches[2]
will contain the trimmed string - make sure its length is not zero and replace the whole string with $1="$2"
and append it (I don't speak c#)
This regex assumes that
- The part before
=
is a single word consisting of only alphanumeric characters and underscores. - The string inside the double quotes are free of double quotes.
This should help, replace [] with "" How to extract the contents of square brackets in a string of text in c# using Regex
var regex = new Regex(@"\""([^\""]*)\""");
foreach(string x in strings)
{
var matches = regex.Matches(x);
if (matches.Count > 0)
{
var matchedValue = matches[0].Groups[1].Value;
z.Append(matchedValue);
}
}
精彩评论