I need to recover each number in a glued string
For example, from these strings:
string test = "number1+3"
string test1 = "number 1+4"
I want to recover (1 and 3) and (1 and 4)
How can I do this?
CODE
string test= "number1+3";
List<int> res;
string[] digits= Regex.Split(test, #"\D+");
foreach (string value in digits)
{
int number;
if (int.TryParse(value, out number))
{
res.Add(number)
}
}
This regex should work
string pattern = #"\d+";
string test = "number1+3";
foreach (Match match in Regex.Matches(test, pattern))
Console.WriteLine("Found '{0}' at position {1}",
match.Value, match.Index);
Note that if you intend to use it multiple times, it's better, for performance reasons, to create a Regex instance than using this static method.
var res = new List<int>();
var regex = new Regex(#"\d+");
void addMatches(string text) {
foreach (Match match in regex.Matches(text))
{
int number = int.Parse(match.Value);
res.Add(number);
}
}
string test = "number1+3";
addMatches(test);
string test1 = "number 1+4";
addMatches(test1);
MSDN link.
Fiddle 1
Fiddle 2
This calls for a regular expression:
(\d+)\+(\d+)
Test it
Match m = Regex.Match(input, #"(\d+)\+(\d+)");
string first = m.Groups[1].Captures[0].Value;
string second = m.Groups[2].Captures[0].Value;
An alternative to regular expressions:
string test = "number 1+4";
int[] numbers = test.Replace("number", string.Empty, StringComparison.InvariantCultureIgnoreCase)
.Trim()
.Split("+", StringSplitOptions.RemoveEmptyEntries)
.Select(x => Convert.ToInt32(x))
.ToArray();
Related
Someone knows how to find the longest substring composed of letters using using MatchCollection.
public static Regex pattern2 = new Regex("[a-zA-Z]");
public static string zad3 = "ala123alama234ijeszczepsa";
You can loop over all matches and get the longest:
string max = "";
foreach (Match match in Regex.Matches(zad3, "[a-zA-Z]+"))
if (max.Length < match.Value.Length)
max = match.Value;
Try this:
MatchCollection matches = pattern2.Matches(txt);
List<string> strLst = new List<string>();
foreach (Match match in matches)
strLst.Add(match.Value);
var maxStr1 = strLst.OrderByDescending(s => s.Length).First();
or better way :
var maxStr2 = matches.Cast<Match>().Select(m => m.Value).ToArray().OrderByDescending(s => s.Length).First();
best solution for your task is:
string zad3 = "ala123alama234ijeszczepsa54dsfd";
string max = Regex.Split(zad3,#"\d+").Max(x => x);
You must change your Regex pattern to include the repetition operator + so that it matches more than once.
[a-zA-Z] should be [a-zA-Z]+
You can get the longest value using LINQ. Order by the match length descending and then take the first entry. If there are no matches the result is null.
string pattern2 = "[a-zA-Z]+";
string zad3 = "ala123alama234ijeszczepsa";
var matches = Regex.Matches(zad3, pattern2);
string result = matches
.Cast<Match>()
.OrderByDescending(x => x.Value.Length)
.FirstOrDefault()?
.Value;
The string named result in this example is:
ijeszczepsa
Using linq and the short one:
string longest= Regex.Matches(zad3, pattern2).Cast<Match>()
.OrderByDescending(x => x.Value.Length).FirstOrDefault()?.Value;
you can find it in O(n) like this (if you do not want to use regex):
string zad3 = "ala123alama234ijeszczepsa";
int max=0;
int count=0;
for (int i=0 ; i<zad3.Length ; i++)
{
if (zad3[i]>='0' && zad3[i]<='9')
{
if (count > max)
max=count;
count=0;
continue;
}
count++;
}
if (count > max)
max=count;
Console.WriteLine(max);
I have a text say:
Hello
abc
Hello
def
Hello
I want to convert it to
Hello1
abc
Hello2
abc
Hello3
i.e I need to append a number after each occurrence of "Hello" text.
Currently I have written this code:
var xx = File.ReadAllText("D:\\test.txt");
var regex = new Regex("Hello", RegexOptions.IgnoreCase);
var matches = regex.Matches(xx);
int i = 1;
foreach (var match in matches.Cast<Match>())
{
string yy = match.Value;
xx = Replace(xx, match.Index, match.Length, match.Value + (i++));
}
and the Replace method above used is:
public static string Replace(string s, int index, int length, string replacement)
{
var builder = new StringBuilder();
builder.Append(s.Substring(0, index));
builder.Append(replacement);
builder.Append(s.Substring(index + length));
return builder.ToString();
}
Currently the above code is not working and is replacing the text in between.
Can you help me fixing that?
Assuming Hello is just a placeholder for a more complex pattern, here is a simple fix: use a match evaluator inside Regex.Replace where you may use variables:
var s = "Hello\nabc\nHello\ndef\nHello";
var i = 0;
var result = Regex.Replace(
s, "Hello", m => string.Format("{0}{1}",m.Value,++i), RegexOptions.IgnoreCase);
Console.WriteLine(result);
See the C# demo
Just need a little push here. I have a file with data like
xyz buildinfo app_id="12345" asf
sfsdf buildinfo app_id="12346" wefwef
...
I need to get a string array with the number following app_id=. Below code gives me all matches and i am able to get the count( Regex.Matches(text, searchPattern).Count). But I need the actual items into an array.
string searchPattern = #"app_id=(\d+)";
var z = Regex.Matches(text, searchPattern);
I think you're saying you want the items (numbers) without the app_id part. You want to use a Positive Lookbehind
string text = #"xyz buildinfo app_id=""12345"" asf sfsdf buildinfo app_id=""12346"" wefwef";
string searchPattern = #"(?<=app_id="")(\d+)";
var z = Regex.Matches(text, searchPattern)
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
(?<=app_id="") will match the pattern, but not include it in the capture
You can take a look at the documentation.
Quoting it you can use this code:
string pattern = #"app_id=(\d+)";
string input = "xyz buildinfo app_id="12345" asf sfsdf buildinfo app_id="12346" efwef";
Match match = Regex.Match(input, pattern);
if (match.Success) {
Console.WriteLine("Matched text: {0}", match.Value);
for (int ctr = 1; ctr <= match.Groups.Count - 1; ctr++) {
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
int captureCtr = 0;
foreach (Capture capture in match.Groups[ctr].Captures) {
Console.WriteLine(" Capture {0}: {1}",
captureCtr, capture.Value);
captureCtr += 1;
}
}
}
So here is my example
string test = "Hello World, I am testing this string.";
string[] myWords = {"testing", "string"};
How do I check if the string test contains any of the following words? If it does contain how do I make it so that it can replace those words with a number of asterisks equal to the length of that?
You can use a regex:
public string AstrixSomeWords(string test)
{
Regex regex = new Regex(#"\b\w+\b");
return regex.Replace(test, AsterixWord);
}
private string AsterixWord(Match match)
{
string word = match.Groups[0].Value;
if (myWords.Contains(word))
return new String('*', word.Length);
else
return word;
}
I have checked the code and it seems to work as expected.
If the number of words in myWords is large you might consider using HashSet for better performance.
bool cont = false;
string test = "Hello World, I am testing this string.";
string[] myWords = { "testing", "string" };
foreach (string a in myWords)
{
if( test.Contains(a))
{
int no = a.Length;
test = test.Replace(a, new string('*', no));
}
}
var containsAny = myWords.Any(x => test.Contains(x));
Something like this
foreach (var word in mywords){
if(test.Contains(word )){
string astr = new string("*", word.Length);
test.Replace(word, astr);
}
}
EDIT: Refined
How can I get numbers between brackets of this text with regex in C#?
sample text :
"[1]Ali ahmadi,[2]Mohammad Razavi"
result is : 1,2
My C# code is :
string result = null;
string[] digits = Regex.Split(Text, #"[\d]");
foreach (string value in digits)
{
result += value + ",";
}
return result.Substring(0,result.Length - 1);
string s = "[1]Ali ahmadi,[2]Mohammad Razavi";
Regex regex = new Regex(#"\[(\d+)\]", RegexOptions.Compiled);
foreach (Match match in regex.Matches(s))
{
Console.WriteLine(match.Groups[1].Value);
}
This will capture the numbers between brackets (\d+), and store them in the first matched group (Groups[1]).
DEMO.
Using a Linq-based approach on João's answer:
string s = "[1]Ali ahmadi,[2]Mohammad Razavi";
var digits = Regex.Matches(s, #"\[(\d+)\]")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
foreach (var match in digits)
{
Console.WriteLine(match);
}
DEMO