parse value from given string using Regex [duplicate] - c#

This question already has an answer here:
C# verbatim string literal not working. Very Strange backslash always double
(1 answer)
Closed 6 years ago.
I have this string:
String str = "Displaying bills 1 - 20 of 10000 in total";
And i want to parse the total value, 10000 in this case.
This is what i have try:
Regex regex = new Regex(#"\\d+(?=\\s*in total)");
Match match = regex.Match("Displaying bills 1 - 20 of 10000 in total");
if (match.Success)
{
Console.WriteLine(match.Value);
}
And currently this now succeed.

string text = "Displaying bills 1 - 20 of 10000 in total";
Regex r = new Regex(Regex.Escape("of") +"(.*?)"+Regex.Escape("in"));
MatchCollection matches = r.Matches(text);
MessageBox.Show(matches[0].Groups[1].Value);

As mentioned in comment by #juharr, you just need to remove the double backslashes. The # at the beginning of the string marks it as a verbatim string, which doesn't require special characters to be escaped.

Related

Regex don't match more than once the pattern in incoming string [duplicate]

This question already has answers here:
What do ^ and $ mean in a regular expression?
(2 answers)
Difference between \b and \B in regex
(10 answers)
Closed 2 years ago.
I have a task to write a regex for a valid name. It has to consist two words, each word starts with capital letter, afterwards contains only lowercase letters, should be at least two letters long and the words are separated by a space.
string input = "Stephen King, Bruce hatow, eddie Lee, AShley Greene, Test Testov, Ann Grey";
string pattern = #"^\b[A-Z][a-z]{1,}\s\b[A-Z][a-z]{1,}$";
MatchCollection output = Regex.Matches(input, pattern);
foreach (Match item in output)
{
Console.Write(item);
}
My pattern matches only if the string has one name. e.g. string input = "Stephen King". Is there a way to do it with string or I should use List of strings and check each one of them
Try removing the starting and ending anchors ^ and $. Instead, replace them with word boundaries, allowing for a first/last name match to occur anywhere in the input string:
string input = "Stephen King, Bruce hatow, eddie Lee, AShley Greene, Test Testov, Ann Grey";
string pattern = #"\b[A-Z][a-z]{1,}\s[A-Z][a-z]{1,}\b";
MatchCollection output = Regex.Matches(input, pattern);
foreach (Match item in output)
{
Console.Write(item + "\n");
}
This prints:
Stephen King
Test Testov

Regex not able to parse last group [duplicate]

This question already has answers here:
What is the difference between .*? and .* regular expressions?
(3 answers)
Closed 3 years ago.
This is the test. I expect the last group to be ".png", but this pattern returns "" instead.
var inputStr = #"C:\path\to\dir\[yyyy-MM-dd_HH-mm].png";
var pattern = #"(.*?)\[(.*?)\](.*?)";
var regex = new Regex(pattern);
var match = regex.Match(inputStr);
var thirdGroupValue = match.Groups[3].Value;
// ✓ EXPECTED: ".png"
// ✗ CURRENT: ""
The 1st and 2nd groups work fine.
This is because you made the * in Group 3 lazy:
(.*?)\[(.*?)\](.*?)
^
here
This means it will match as little as possible. What's the least .* can match? An empty string!
You can learn more about lazy vs greedy here.
You can fix this either by removing ?, making it greedy, or put a $ at the end, telling it to match until the end of the string:
(.*?)\[(.*?)\](.*)
or
(.*?)\[(.*?)\](.*?)$

Get value between parentheses [duplicate]

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 4 years ago.
I need to get the all strings that sit between open and closed parentheses. An example string is as follows
[CDATA[[(MyTag),xi(Tag2) ]OT(OurTag3).
The output needs to be an array with MyTag, Tag2, OurTag3 i.e. The strings need to have the parentheses removed.
The code below works but retains the parentheses. How do I adjust the regex pattern to remove the parentheses from the output?
string pattern = #"\(([^)]*)\)";
string MyString = "[CDATA[[(MyTag),xi(Tag2) ]OT(OurTag3)";
Regex re = new Regex(pattern);
foreach (Match match in re.Matches(MyString))
{
Console.WriteLine(match.Groups[1]); // print the captured group 1
}
You should be able to use the following:
(?<=\().+?(?=\))
(?<=() - positive lookbehind for (
.*? - non greedy match for the content
(?=)) - positive lookahead for )

Split a string after reading square brackets in c# [duplicate]

This question already has answers here:
splitting a string based on multiple char delimiters
(7 answers)
Closed 5 years ago.
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string new = test.Trim("[");
I want output "AccoutNumber".
I have tried the below code but not getting the desired result:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[');
string newvalue = test[1];
Just use Split with two delimiters:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[', ']');
string newvalue = test[1];
You can also use Regex:
string test = "Account.Parameters[\"AccountNumber\"].Caption";
var match = System.Text.RegularExpressions.Regex.Match(test, ".*?\\.Parameters\\[\"(.*?)\"]");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
.*? is a non greedy wildcart capture, so it will match your string until it reaches the next part (in our case, it will stop at .Parameters[", match the string, and then at "])
It will match .Parameters["..."]., and extract the "..." part.
you can do a Split to that string...
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string output = test.Split('[', ']')[1];
Console.WriteLine(output);

Regex for decimal value and optional string

I'm looking for a Regex to validate a rating (1-10) + optional text.
Rating is a decimal, with 1 point, which can use both dot or comma separator.
Followed by an optional space + string.
Valid
7
7,5
7.5
7,5 This is my string
7.5 Hello
Invalid
7,75
11
7This is my string
7.This is my string
10.5 string
I've got this for getting the decimal values, but I'm not sure how to get the optional text behind it.
^(10|\d)([\.\,]\d{1,1})?$
Judging by your examples, the space after the initial number is not optional. Thus, the pattern you may use is
^(?:10|[1-9](?:[.,][0-9])?)(?:\s.*)?$
or - since a partial match with Regex.IsMatch is enough to validate the string - replace (?:\s.*)?$ with a negative lookahead (?!\S) that will require a whitespace or end of string after the number:
^(?:10|[1-9](?:[.,][0-9])?)(?!\S)
^^^^^^^
See the regex demo
Details:
^ - start of a string
(?:10|[1-9](?:[.,][0-9])?) - either 10 or a digit from 1 to 9 followed with an optional sequence of a , or . and any single digit and then...
(?:\s.*)?$ - an optional sequence of any whitespace followed with any chars up to the end of string - OR -
(?!\S) - a negative lookahead that fails the match if there is no non-whitespace char immediately to the right of the current position.
C# test:
var strs = new List<string> { "7","7,5","7.5","7,5 This is my string","7.5 Hello","7,75","11","7This is my string","7.This is my string","10.5 string"};
var pattern = #"^(?:10|[1-9](?:[.,][0-9])?)(?:\s.*)?$";
foreach (var s in strs)
if (Regex.IsMatch(s, pattern))
Console.WriteLine("{0} is correct.", s);
else
Console.WriteLine("{0} is invalid.", s);
Output:
7 is correct.
7,5 is correct.
7.5 is correct.
7,5 This is my string is correct.
7.5 Hello is correct.
7,75 is invalid.
11 is invalid.
7This is my string is invalid.
7.This is my string is invalid.
10.5 string is invalid.

Categories