Regex pattern to grab all the numbers in between square brackets? - c#

I'm trying to create a regex pattern to grab all the numbers from a given string which are in between square brackets and separated by commas. The output should be like so,
Number1 = 45
Number2 = 66
And so on... All I have so far is a pattern that greedy grabs everything in between square brackets.
string input3;
//string pattern = #"\b\w+es\b";
string pattern = #"\[(.*?)\]";
//Regex regex = new Regex("[*]");
Console.WriteLine("Enter string to search: ");
input3 = Console.ReadLine();
//Console.WriteLine(input3);
List<string> substrings = new List<string>();
int count = 1;
foreach (Match match in Regex.Matches(input3, pattern)) {
string substring = string.Format("Number{0} = '{1}'",count,match);
count++;
Console.WriteLine(substring);
substrings.Add(substring);
}
string[] subStringArray = substrings.ToArray();
}
Should I just create two patterns, the greedy one and then a second pattern to search the greedy output for all numbers separated by commas? Or would it be more efficient to just create a single pattern?

You said that your string is
string which are in between square brackets and separated by commas.
I guess the input is something like that
[1,2,3,4,5,6]
So you can use this regex to get numbers
var numbers = Regex.Match("[1,2,3,4,5,6]", #"\[(?<numbers>[\d,]+)\]").Groups["numbers"].Value;
And then split by , to get a collection of numbers
var collectionOfNumbers = numbers.Split(',');
And to display this string Number1 = 45
Lets us a litle bit of LINQ to do that
C# 6 syntax
var strings = numbers.Split(',').Select((number, i) => $"Number{i + 1} = {number}");
Console.WriteLine(string.Join("\n", strings))
C# <= 5 syntax
var strings = numbers.Split(',').Select((number, i) => string.Format("Number{0} = {1}", i+1, number));
Console.WriteLine(string.Join("\n", strings))
And this is the ouput
Number1 = 1
Number2 = 2
Number3 = 3
Number4 = 4
Number5 = 5
Number6 = 6
Another example with inpunt: Foo Bar [45,66]
C# 6 syntax
var numbers = Regex.Match("Foo Bar [45,66]", #"\[(?<numbers>[\d,]+)\]").Groups["numbers"].Value;
var strings = numbers.Split(',').Select((number, i) => $"Number{i + 1} = {number}");
Console.WriteLine(string.Join("\n", strings))
C# <= 5 syntax
var numbers = Regex.Match("Foo Bar [45,66]", #"\[(?<numbers>[\d,]+)\]").Groups["numbers"].Value;
var strings = numbers.Split(',').Select((number, i) => string.Format("Number{0} = {1}", i+1, number));
Console.WriteLine(string.Join("\n", strings))
The output is
Number1 = 45
Number2 = 66

Related

How to separate sting with comma plus 8 digits

I want to split a long string (that contains only numbers) to string arr 0f numbers with 8 digits after the comma.
for example:
input:
string str = "45.00019821162.206580920.032150970.03215097244.0031982274.245303020.014716900.046867870.000198351974.613444580.391664580.438532450.00020199 3499.19734739 0.706802871.145335320.000202002543.362378010.513759201.659094520.000202102.391733720.000483371.65957789"
output:
string[] Arr=
"
45.00019821 162.20658092 234.03215097 123123.03215097
255.00019822 74.24530302 23422.01471690 1.04686787
12.00019835 1974.61344458 234.39166458 123212.43853245
532.00020199 3499.19734739 878.70680287 1.14533532
1234.00020200 2543.36237801 23.51375920 1.65909452
12221.00020210 2.39173372 0.00048337 1.65957789"
EDIT:
I try use
String.Format("{0:0.00000000}", str);
or some SubString such as:
public static string GetSubstring(string input, int count, char delimiter)
{
return string.Join(delimiter.ToString(), input.Split(delimiter).Take(count));
}
with no success.
You can split the string using Regex:
var strRegex = #"(?<num>\d+\.\d{8})";
var myRegex = new Regex(strRegex, RegexOptions.None);
foreach (Match myMatch in myRegex.Matches(str))
{
var part = myMatch.Groups["num"].Value;
// convert 'part' to double and store it wherever you want...
}
More compact version:
var myRegex = new Regex(#"(?<num>\d*\.\d{8})", RegexOptions.None);
var myNumbers = myRegex.Matches(str).Cast<Match>()
.Select(m => m.Groups["num"].Value)
.Select(v => Convert.ToDouble(v, CultureInfo.InvariantCulture));
The input string str can be converted to the desired output as follows.
static IEnumerable<string> NumberParts(string iString)
{
IEnumerable<char> iSeq = iString;
while (iSeq.Count() > 0)
{
var Result = new String(iSeq.TakeWhile(Char.IsDigit).ToArray());
iSeq = iSeq.SkipWhile(Char.IsDigit);
Result += new String(iSeq.Take(1).ToArray());
iSeq = iSeq.Skip(1);
Result += new String(iSeq.Take(8).ToArray());
iSeq = iSeq.Skip(8);
yield return Result;
}
}
The parsing method above can be called as follows.
var Parts = NumberParts(str).ToArray();
var Result = String.Join(" ", Parts);
This would be the classical for-loop version of it, (no magic involved):
// split by separator
string[] allparts = str.Split('.');
// Container for the resulting numbers
List<string> numbers = new List<string>();
// Handle the first number separately
string start = allparts[0];
string decimalPart ="";
for (int i = 1; i < allparts.Length; i++)
{
decimalPart = allparts[i].Substring(0, 8);
numbers.Add(start + "." + decimalPart);
// overwrite the start with the next number
start = allparts[i].Substring(8, allparts[i].Length - 8);
}
EDIT:
Here would be a LINQ Version yielding the same result:
// split by separator
string[] allparts = str.Split('.');
IEnumerable<string> allInteger = allparts.Select(x => x.Length > 8 ? x.Substring(8, x.Length - 8) : x);
IEnumerable<string> allDecimals = allparts.Skip(1).Select(x => x.Substring(0,8));
string [] allWholeNumbers = allInteger.Zip(allDecimals, (i, d) => i + "." + d).ToArray();
The shortest way without regex:
var splitted = ("00000000" + str.Replace(" ", "")).Split('.');
var result = splitted
.Zip(splitted.Skip(1), (f, s) =>
string.Concat(f.Skip(8).Concat(".").Concat(s.Take(8))))
.ToList()
Try it online!

How to count 2 or 3 letter words in a string using asp c#

How to count 2 or 3 letter words of a string using asp csharp, eg.
string value="This is my string value";
and output should look like this
2 letter words = 2
3 letter words = 0
4 letter words = 1
Please help, Thanks in advance.
You can try something like this:
split sentence by space to get array of words
group them by length of word (and order by that length)
iterate through every group and write letter count and number of words with that letter count
code
using System.Linq;
using System.Diagnostics;
...
var words = value.Split(' ');
var groupedByLength = words.GroupBy(w => w.Length).OrderBy(x => x.Key);
foreach (var grp in groupedByLength)
{
Debug.WriteLine(string.Format("{0} letter words: {1}", grp.Key, grp.Count()));
}
First of all you need to decide what counts as a word. A naive approach is to split the string with spaces, but this will also count commas. Another approach is to use the following regex
\b\w+?\b
and collect all the matches.
Now you got all the words in a words array, we can write a LINQ query:
var query = words.Where(x => x.Length >= 2 && x.Length <= 4)
.GroupBy(x => x.Length)
.Select(x => new { CharCount = x.Key, WordCount = x.Count() });
Then you can print the query out like this:
query.ToList().ForEach(Console.WriteLine);
This prints:
{ CharCount = 4, WordCount = 1 }
{ CharCount = 2, WordCount = 2 }
You can write some code yourself to produce a more formatted output.
If i understood your question correctly
You can do it using dictionary
First split the string by space in this case
string value = "This is my string value";
string[] words = value.Split(' ');
Then loop trough array of words and set the length of each word as a key of dictionary, note that I've used string as a key, but you can modify this to your needs.
Dictionary<string, int> latteWords = new Dictionary<string,int>();
for(int i=0;i<words.Length;i++)
{
string key = words[i].Length + " letter word";
if (latteWords.ContainsKey(key))
latteWords[key] += 1;
else
latteWords.Add(key, 1);
}
And the output would be
foreach(var ind in latteWords)
{
Console.WriteLine(ind.Key + " = " + ind.Value);
}
Modify this by wish.

C#_How to Multiply elements between Two string

-I have two string(non-space):
string input1 = "bike2car5ship86plan3";
string input2 = "car382bike50ship92yoyo2";
-I've tried regular expressions Match and Linq, but my result is not like hoping:
-How to make them like this result:
Bike 2 x 50 = 100
Car 5 x 382 = 1910
Ship 86 x 92 = 7912
-----------------------------
Total = 9922
Note: plan3 and yoyo2 does not appear in both input1 and input2 so they don't enter the result written.
Try using Linq and regular expressions, something like this:
string input1 = "bike2car5ship86plan3";
string input2 = "car382bike50ship92yoyo2";
var inputs1 = Regex
.Matches(input1, "([a-zA-Z]+)([0-9]+)")
.OfType<Match>()
.ToDictionary(match => match.Groups[1].Value,
match => int.Parse(match.Groups[2].Value));
var inputs2 = Regex
.Matches(input2, "([a-zA-Z]+)([0-9]+)")
.OfType<Match>()
.ToDictionary(match => match.Groups[1].Value,
match => int.Parse(match.Groups[2].Value));
TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
var data = inputs1
.Where(pair => inputs2.ContainsKey(pair.Key))
.OrderBy(pair => pair.Key)
.Select(pair => new {
Name = textInfo.ToTitleCase(pair.Key),
Quantity = pair.Value,
Price = inputs2[pair.Key],
Total = pair.Value * inputs2[pair.Key], })
.ToArray();
string table = string.Join(Environment.NewLine, data
.Select(item => string.Format("{0,-5} {1,3} x {2,3} = {3,4}",
item.Name, item.Quantity, item.Price, item.Total)));
string result = string.Join(Environment.NewLine,
table,
new string('-', 25),
string.Format("Total = {0}", data.Sum(pair => pair.Total)));
Console.Write(result);
Outcome:
Bike 2 x 50 = 100
Car 5 x 382 = 1910
Ship 86 x 92 = 7912
-------------------------
Total = 9922
This is simple regex, but you have to do it in multiple steps:
separate every occurrence of word+number
separate the number from word
compare and multiply the findings
To step 1:
as regex you can use "[a-zA-Z]*\d*"
[a-zA-Z]* allows any number of characters followed by a number (\d*)
To step 2:
you can separate the number from the name also with regex ("\d*")
To step 3:
you can add the Matches from the first string to a dictionary like:
myDictionaryForString1.Add(name, value);
and then multiply the values with your values from the second string (same procedure as for the first string to get the values) like:
if (myDictionaryForString1.ContainsKey(name)) {
myResultDictionary.Add(name, myDictionaryForString1[name] * value);
}

C# finding percent of matched words between two string

I have a single string that i want to compare against a list of strings to find the best match.
For example,
string search = "Orange Black Red One Five"
the List of strings could contain the following
l[0] = "Orange Seven Three Black"
l[1] = " Nine Eight Seven Six"
l[2] = " Black Blue Purple Red Five Four Nine Ten"
l[0] contains 2 matches
l[1] contains 0 matches
l[2] contains 3 matches
so the program would choose l[2] as the best match, with a 60% match.
How would I compare two strings like this?
var s = search.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries);
var res1 = (from string part in l
select new
{
list = part,
count = part.Split(new char[] {' '}).Sum(p => s.Contains(p) ? 1 : 0)
}).OrderByDescending(p=> p.count).First();
Console.Write(res1.count);
Split the strings in to arrays.
Determine the number of matches.
Divide.
...
Profit!
Code:
double Compare(string a, string b)
{
var aWords = a.Split(' ');
var bWords = b.Split(' ');
double matches = (double)aWords.Count(x => bWords.Contains(x));
return matches / (double)aWords.Count();
}
Edit: Or, if you just want to get the match count...
int Matches(string a, string b)
{
var aWords = a.Split(' ');
var bWords = b.Split(' ');
return aWords.Count(x => bWords.Contains(x));
}

How to keep the delimiters of Regex.Split?

I'd like to split a string using the Split function in the Regex class. The problem is that it removes the delimiters and I'd like to keep them. Preferably as separate elements in the splitee.
According to other discussions that I've found, there are only inconvenient ways to achieve that.
Any suggestions?
Just put the pattern into a capture-group, and the matches will also be included in the result.
string[] result = Regex.Split("123.456.789", #"(\.)");
Result:
{ "123", ".", "456", ".", "789" }
This also works for many other languages:
JavaScript: "123.456.789".split(/(\.)/g)
Python: re.split(r"(\.)", "123.456.789")
Perl: split(/(\.)/g, "123.456.789")
(Not Java though)
Use Matches to find the separators in the string, then get the values and the separators.
Example:
string input = "asdf,asdf;asdf.asdf,asdf,asdf";
var values = new List<string>();
int pos = 0;
foreach (Match m in Regex.Matches(input, "[,.;]")) {
values.Add(input.Substring(pos, m.Index - pos));
values.Add(m.Value);
pos = m.Index + m.Length;
}
values.Add(input.Substring(pos));
Say that input is "abc1defg2hi3jkl" and regex is to pick out digits.
String input = "abc1defg2hi3jkl";
var parts = Regex.Matches(input, #"\d+|\D+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
Parts would be: abc 1 defg 2 hi 3 jkl
For Java:
Arrays.stream("123.456.789".split("(?<=\\.)|(?=\\.)+"))
.forEach((p) -> {
System.out.println(p);
});
outputs:
123
.
456
.
789
inspired from this post (How to split string but keep delimiters in java?)
Add them back:
string[] Parts = "A,B,C,D,E".Split(',');
string[] Parts2 = new string[Parts.Length * 2 - 1];
for (int i = 0; i < Parts.Length; i++)
{
Parts2[i * 2] = Parts[i];
if (i < Parts.Length - 1)
Parts2[i * 2 + 1] = ",";
}
for c#:
Split paragraph to sentance keeping the delimiters
sentance is splited by . or ? or ! followed by one space (otherwise if there any mail id in sentance it will be splitted)
string data="first. second! third? ";
Regex delimiter = new Regex("(?<=[.?!] )"); //there is a space between ] and )
string[] afterRegex=delimiter.Split(data);
Result
first.
second!
third?

Categories

Resources