C# Regular Expressions, string between single quotes - c#

string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
i want to get the text between ' quotes using Regular Expressions.
Can anyone?

Something like this should do it:
string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
Match match = Regex.Match(val, #"'([^']*)");
if (match.Success)
{
string yourValue = match.Groups[1].Value;
Console.WriteLine(yourValue);
}
Explanation of the expression '([^']*):
' -> find a single quotation mark
( -> start a matching group
[^'] -> match any character that is not a single quotation mark
* -> ...zero or more times
) -> end the matching group

You are looking to match GUID's in a string using a regular expression.
This is what you want, I suspect!
public static Regex regex = new Regex(
"(\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-"+
"([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})",RegexOptions.CultureInvariant|RegexOptions.Compiled);
Match m = regex.Match(lineData);
if (m.Succes)
{
...
}

This will extract the text between the first and last single quote on a line:
string input = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
Regex regName = new Regex("'(.*)'");
Match match = regName.Match(input);
if (match.Success)
{
string result = match.Groups[1].Value;
//do something with the result
}

You could use positive lookahead and lookbehind also,
string val = "name='40474740-1e40-47ce-aeba-ebd1eb1630c0'";
Match match = Regex.Match(val, #"(?<=')[^']*(?=')");
if (match.Success)
{
string yourValue = match.Groups[0].Value;
Console.WriteLine(yourValue);
}

Related

How to use regex to find variable name beginning with # in a string expression?

The programmer hope to get two variables day1 and day2 by using regex, all the other variables in string expression beginning with the character # too.
The example of a string expression: #day1 - #day2 > 3
Thanks!
You can simply use positive lookahead here.
string = "#day1 - #day2 > 3";
Regex regex = new Regex("(?<=#)\\w+", RegexOptions.Compiled);
var match = regex.Matches(a);
foreach( var val in match )
{
Console.WriteLine(val);
}
val contains the match values.
You could use a lookbehind to get the variable names, like so:
var regex = new Regex("(?<=#)\\w+");
This will get the words preceded by an # sign

Regex - replacing chars in C# string in specific cases

I want to replace all brackets to another in my input string only when between them there aren't digits. I wrote this working sample of code:
string pattern = #"(\{[^0-9]*?\})";
MatchCollection matches = Regex.Matches(inputString, pattern);
if(matches != null)
{
foreach (var match in matches)
{
string outdateMatch = match.ToString();
string updateMatch = outdateMatch.Replace('{', '[').Replace('}', ']');
inputString = inputString.Replace(outdateMatch, updateMatch);
}
}
So for:
string inputString = "{0}/{something}/{1}/{other}/something"
The result will be:
inputString = "{0}/[something]/{1}/[other]/something"
Is there possibility to do this in one line using Regex.Replace() method?
You may use
var output = Regex.Replace(input, #"\{([^0-9{}]*)}", "[$1]");
See the regex demo.
Details
\{ - a { char
([^0-9{}]*) - Capturing group 1: 0 or more chars other than digits, { and }
} - a } char.
The replacement is [$1], the contents of Group 1 enclosed with square brackets.
Regex.Replace(input, #"\{0}/\{(.+)\}/\{1\}/\{(.+)}/(.+)", "{0}/[$1]/{1}/[$2]/$3")
Could you do this?
Regex.Replace(inputString, #"\{([^0-9]*)\}", "[$1]");
That is, capture the "number"-part, then just return the string with the braces replaced.
Not sure if this is exactly what you are after, but it seems to fit the question :)

Get the Number from a string

I want to trim a string and get the number between special characters.
For example there is a string BC/PO/88/2018 from it i want to get 88.
you can make use of regular expression and extract number
Match match = Regex.Match("BC/PO/88/2018 f" , #"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[0].Value);
}
other way is you can do with the help of String.Split as suggested in comments if you are sure about string coming as input i.e. sure about format of string.
You could use Regular Expressions:
string strRegex = #"[A-Z]{2}/[A-Z]{2}/(?<MyNumber>[0-9]*)/[0-9]{4}";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"BC/PO/88/2018";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}

Regex for a special string pattern on multiple levels

I need to evaluate a string pattern that is something like as given below and I am quite new at writing such complex expressions
<%(ddlValue){DropDownList}[SelectedValue]%>
// this has three part (Control Name) {Control Type} [Control Property]
I tried a whole lot of regex and other tools like RegExr but anything did not worked. I have to do this on four levels, that is as given below in the code. So here is what I have done:
string regex = "/[<%](.*?)[%>]/g"; // Regex to match "<% %>" pattern
Match mtch = Regex.Match(strQuery, regex, RegexOptions.Singleline);
string strControlName = "";
string strControlType = "";
string strControlProp = "";
if (mtch.Success)
{
string strVal = mtch.Value;
Match mtchControlName = Regex.Match(strVal, "/[(]\S)/");
// Regex to match "()" i.e. control name ("ddlValue" in above example)
if (mtchControlName.Success)//Match control Name
{
strControlName = mtchControlName.Value;
Match mtchControlType = Regex.Match(strVal, "/[{]\s[}]/");
// Regex to match "[]" i.e. control type
if (mtchControlType.Success) // Match Control Type
{
strControlType = mtchControlType.Value;
Match mtchControlProp = Regex.Match(strVal, "/[(]\S[)]/");
// Regex to match "[]" i.e. control property
if (mtchControlProp.Success) // Match Control Prop
{
strControlProp = mtchControlProp.Value;
}
}
}
}
You can do this in a single regex. Being as specific as possible, you could do this:
Regex regexObj = new Regex(
#"\( # Match (
( # Capture in group 1:
[^()]* # Any number of characters except ()s
) # End of group 1
\) # Match )
\{([^{}]*)\} # The same for {...} into group 2
\[([^\[\]]*)\] # The same for [...] into group 3",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
Then you case use
Match matchResults = regexObj.Match(subjectString);
to get a Match object. Access the submatches via
matchResults.Groups(n).Value // insert 1, 2 or 3 for n
See it live on regex101.com.
You can use capturing groups in one expression to capture all groups together:
String input = "<%(ddlValue){DropDownList}[SelectedValue]%>";
String pattern = #"<%\((.+)\)\{(.+)\}\[(.+)\]%>";
Match m = Regex.Match(input, pattern);
if (m.Groups.Count == 4)
{
string firstpart = m.Groups[1].ToString();
string secondpart = m.Groups[2].ToString();
string thirdpart = m.Groups[3].ToString();
}
You could use named groups. It makes the code more readable.
Match m = Regex.Match(inputData, #"^<%\((?<ddlValue>[^)]+)\){(?<DropDownList>[^}]+)}\[(?<SelectedValue>[^\]]+)\]%>$");
if (m.Groups.Count == 4)
{
string firstpart = m.Groups["ddlValue"].ToString();
string secondpart = m.Groups["DropDownList"].ToString();
string thirdpart = m.Groups["SelectedValue"].ToString();
}

Regex find first 20 characters after an email stored in variable

string subject = null;
string toFind = "["+emailFound+"]([.20])";
Match match = Regex.Match(messageText, toFind, RegexOptions.IgnoreCase);
if (match.Success)
{
subject = match.Value;
}
MessageBox.Show(subject);
This is code I have so far, I'm really new at regex and not quite sure how it works. How would I get the first 20 characters after "emailFound"
Thanks
No more errors, but now it's just not finding anything after the emailFound...
That's because you need to get the Group value after you check the match instance.
string toFind = Regex.Escape(emailFound) + "(?s)(.{20})";
Match match = Regex.Match(messageText, toFind);
if (match.Success) {
subject = match.Groups[1].Value; // Get the Group value
}
See live demo
You can try this:
string toFind = Regex.Escape(emailFound)+"(?s)(.{20})";
(?s) allows the dot to match newlines (you can remove it and add the RegexOptions.SingleLine in the Match method.)
.{20} twenty characters

Categories