Get the Number from a string - c#

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
}
}

Related

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 :)

Problems with regex in c# only returning a single match

I'm building a regex and I'm missing something as it's not working properly.
my regex logic is trying to look for anything that has #anychars# and return the number of matches on the sentence and not a single match.
Here are a few examples
1- #_Title_# and #_Content_# should return two matches: #_Title_# and #_Content_#.
2- Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_# should return 3 matches: #_TemplateName_# #_Full_Product_Name_# and #_Short_Description_#
and so on. Here is what my regex looks like: ^(.*#_.*_#.*)+$
any thoughts on what I'm doing wrong?
Something as simple as:
#.*?#
Or:
#_.*?_#
If you are trying to match the underscores too (it wasn't clear in the original version of the question). Or:
#_(.*?)_#
Which makes it easier to extract the token between your #_ and _# delimiters as a group.
Should work. The *? is key. It's non-greedy. Otherwise you match everything between the first and last #
So for example:
var str = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#";
var r = new Regex("#_(.*?)_#");
foreach (Match m in r.Matches(str))
{
Console.WriteLine(m.Value + "\t" + m.Groups[1].Value);
}
Outputs:
#_TemplateName_#     TemplateName
#_Full_Product_Name_#    Full_Product_Name
#_Short_Description_#    Short_Description
Try this :
string[] inputs = {
"#Title# and #Content#",
"Product #TemplateName# #_Full_Product_Name_# more text. text text #_Short_Description_#"
};
string pattern = "(?'string'#[^#]+#)";
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine(string.Join(",",matches.Cast<Match>().Select(x => x.Groups["string"].Value).ToArray()));
}
Console.ReadLine();
You regular expression is not correct. In addition, you want to loop through match if you want all matching.
static void Main(string[] args)
{
string input = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#",
pattern = "#_[a-zA-Z_]*_#";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
Console.WriteLine(match.Value);
match = match.NextMatch();
}
Console.ReadLine();
}
Result
Don't use anchors and change your regex to:
(#[^#]+#)
In regex the [^#] expression means any character BUT #
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(#[^#]+#)";
Regex rgx = new Regex(pattern);
string sentence = "#blah blah# asdfasdfaf #somethingelse#";
foreach (Match match in rgx.Matches(sentence))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
}
}

How do I extract a string of text that lies between *>...* using .NET C# regex or anything else?

I have a string like this.
*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*
I wanna extract between *> and * characters.
I tried this pattern which is wrong here below:
string pattern = "\\*\\>..\\*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(seriGelen);
if (matches.Count > 0)
{
foreach (Match match in matches)
MessageBox.Show("{0}", match.Value);
}
You can use simple regex:
(?<=\*>).*?(?=\*)
Sample code:
string text = "*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*";
string[] values = Regex.Matches(text, #"(?<=\*>).*?(?=\*)")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
Looks like there are can be very different values (UPD: there was an integer positive value). So, let me to not check numbers format. Also I will consider that *> and >, and also * are just different variants of delimiters.
I'd like to suggest the following solution.
(?<=[>\*])([^>\*]+?)(?=[>\*]+)
(http://regex101.com/r/mM7nK1)
Not sure it is ideal. Will only works if your input starts and ends with delimiters, but will allow to you to use matches instead groups, as your code does.
========
But you know, why wouldn't you use String.Split function?
var toprint = seriGelen.Split(new [] {'>', '*'}, StringSplitOptions.RemoveEmptyEntries);
Is there an error at the beginning of the string? Missing an asterisk after first number? >-0.0532>-0.0534*>
If not try this.
>([-+]?[0-9]*\.?[0-9]+)\*
C# Code
string strRegex = #">([-+]?[0-9]*\.?[0-9]+)\*";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
string strTargetString = #">-0.0532>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}

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

C# Regular Expressions, string between single quotes

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);
}

Categories