C# Regex extract certain digits from a number - c#

I am trying to extract the digits from 10:131186; and get 10131186 without the : and ;.
What is the Regex pattern I need to create?
var input = "10:131186;";
string pattern = ":(.*);";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value);
With the above code, I am getting :131186; instead of 10121186.

Why you need to use Regex. It's slower than using string.Replace method
string input = "10:131186;";
input = input.Replace(":", "");
input = input.Replace(";", "");
Console.WriteLine(input);

You can try using Regex.Replace:
var input = "10:131186;";
string pattern = #"(\d+):(\d+);";
string res = Regex.Replace(input, pattern, "$1$2");
Console.WriteLine(res);
and you can also use Split with Join:
var input = "10:131186;";
Console.WriteLine(string.Join("", input.Split (new char[] { ':', ';' }, StringSplitOptions.RemoveEmptyEntries)));

Please try this..
string input = "10:131186;";
input = input.Replace(":", String.Empty).Replace(";", string.Empty);

Just print the group index 1.
var input = "10:131186;";
string pattern = ":(.*);";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value[1]);
or use assertions.
var input = "10:131186;";
string pattern = "(?<=:).*?(?=;)";
Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Value);

You could use the pattern \\d+ to match digits in the string and concatenate them into a single string.
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "10:131186;";
MatchCollection mCol = Regex.Matches(input, "\\d+");
StringBuilder sb = new StringBuilder();
foreach (Match m in mCol)
{
sb.Append(m.Value);
}
Console.WriteLine(sb);
}
}
Results:
10131186
Demo

Related

C# RegEx to find values within a string

I am new to RegEx. I have a string like following. I want to get the values between [{# #}]
Ex: "Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"
I would like to get the following values from the above string.
"John",
"ABC Bank",
"Houston"
Based on the solution Regular Expression Groups in C#.
You can try this:
string sentence = "Employee name is [{#john#}], works for [{#ABC BANK#}],
[{#Houston#}]";
string pattern = #"\[\{\#(.*?)\#\}\]";
foreach (Match match in Regex.Matches(sentence, pattern))
{
if (match.Success && match.Groups.Count > 0)
{
var text = match.Groups[1].Value;
Console.WriteLine(text);
}
}
Console.ReadLine();
Based on the solution and awesome breakdown for matching patterns inside wrapping patterns you could try:
\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]
Where \[\{\# is your escaped opening sequence of [{# and \#\}\] is the escaped closing sequence of #}].
Your inner values are in the matching group named Text.
string strRegex = #"\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
string strTargetString = #"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var text = myMatch.Groups["Text"].Value;
// TODO: Do something with it.
}
}
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Test("the quick brown [{#fox#}] jumps over the lazy dog."));
Console.ReadLine();
}
public static string Test(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
var result = System.Text.RegularExpressions.Regex.Replace(str, #".*\[{#", string.Empty, RegexOptions.Singleline);
result = System.Text.RegularExpressions.Regex.Replace(result, #"\#}].*", string.Empty, RegexOptions.Singleline);
return result;
}
}
}

Regular Expression in c# to find letter then \ with capital letter for letter and Shift press form of other charecter?

I want to convert a string like
m\anoj ku\mar m\a\noj
to
Manoj kUmar MAnoj
how can i do this using c#
string convert(string text)
{
string pattern = #"$1\\";
string repPattern =#"";
string returnText = Regex.Replace(text, repPattern, pattern);
return returnText;
}
What is assigneed to repPattern ? to get result
Try following:
var input = #"m\anoj ku\mar m\a\noj";
var pattern = new Regex(#"([a-z])\\");
var replaced = pattern.Replace(input, m => m.Groups[1].ToString().ToUpper());
Console.WriteLine(replaced);
UPDATE
Map digits to shift-pressed form:
string text= #"m\an1oj ku\mar m\a\no9j";
char[] shiftPressForms = ")!##$%^&*(".ToCharArray();
Regex pattern = new Regex(#"([a-z])\\");
Regex pattern_digit = new Regex(#"\d");
string replaced = pattern.Replace(text, m => m.Groups[1].ToString().ToUpper());
replaced = pattern_digit.Replace(replaced, m => shiftPressForms[int.Parse(m.Value)].ToString());
Console.WriteLine(replaced);

Get everything before the second given character using Regular Expression

I have a list of strings like
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[AB1].[XX3].sdfnwoaenwaf
[AB2].[XX1].sdfnwoaenwaf
How can I get everything before the second dot? e.g. [ABC].[XXX] for the first one.
(.*)\. is the regex you need. You may test on http://regexhero.net/tester/
You could try a regex or use the LastIndexOf method of the String class or the Split method of the String class.
Regex
var toMatch = "[ABC].[XXX].sdfnwoaenwaf";
var pattern = new Regex("(.*?\\..*?)(:?\\.)");
var beforeSecondDot = pattern.Match(toMatch);
var stringBeforeSecondDot = beforeSecondDot.Groups[1].Value;
String.LastIndexOf
var toMatch = "[ABC].[XXX].sdfnwoaenwaf";
var indexOfLastDot = toMatch.LastIndexOf('.');
var beforeSecondDot = toMatch.Substring(0, indexOfLastDot);
String.Split
var toMatch = "[ABC].[XXX].sdfnwoaenwaf";
var parts = toMatch.Split('.');
var beforeSecondDot = String.Join(".", parts.Take(2));
string x = "[AB2].[XX1].sdfnwoaenwaf";
Regex regex = new Regex("([^.]+\\.[^.]+)\\.");
Match match = regex.Match(x);
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
Output:
[AB2].[XX1]
List<string> finalStrings = new List<string>();
List<string> strings = new List<string>();
strings.Add("[ABC].[XXX].sdfnwoaenwaf");
strings.Add("[ABC].[XXX].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
strings.Add("[ABC].[XX3].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
foreach (var item in strings)
{
Regex rex = new Regex("(.*)\\.");
string[] y = rex.Split(item);
finalStrings.Add(y[1]);
}

SplitString or SubString or?

Is there (.NET 3.5 and above) already a method to split a string like this:
string str = "{MyValue} something else {MyOtherValue}"
result: MyValue , MyOtherValue
Do like:
string regularExpressionPattern = #"\{(.*?)\}";
Regex re = new Regex(regularExpressionPattern);
foreach (Match m in re.Matches(inputText))
{
Console.WriteLine(m.Value);
}
System.Console.ReadLine();
dont forget to add new namespace: System.Text.RegularExpressions;
You can use regular expressions to do it. This fragment prints MyValue and MyOtherValue.
var r = new Regex("{([^}]*)}");
var str = "{MyValue} something else {MyOtherValue}";
foreach (Match g in r.Matches(str)) {
var s = g.Groups[1].ToString();
Console.WriteLine(s);
}
MatchCollection match = Regex.Matches(str, #"\{([A-Za-z0-9\-]+)\}", RegexOptions.IgnoreCase);
Console.WriteLine(match[0] + "," + match[1]);
Something like this:
string []result = "{MyValue} something else {MyOtherValue}".
Split(new char[]{'{','}'}, StringSplitOptions.RemoveEmptyEntries)
string myValue = result[0];
string myOtherValue = result[2];

Replace and delete with Regular expression?

if (Result.Contains("http://"))
{
string pattern = #"(http://)";
theend = Result.Substring(Result.IndexOf("http://"));
Regex rgx = new Regex(pattern);
string replacement = ""+theend+" ";
Result = rgx.Replace(Result, replacement);
}
The result is normal link (a href) and after that there is a string http://. How do I get only a link?
Not clear exactly what are you trying to do. how does the input Result looks like.
if Result only contains the URL then just change:
Result = rgx.Replace(Result, replacement);
to
Result = replacement;
Update:
Anyway, You can use this function:
private string ConvertUrlsToLinks(string msg) {
string regex = #"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:#=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

Categories

Resources