Using lambda expression to select array element where it matches in string - c#

I am trying to select an element in array, that matches something in a string.
For example:
string[] splitChar = new string[] { "+=", "-=" };
string content = "5+=2";
So i want to check if content, contains something from splitChar, and if it does then select the value so it can be assigned to a string variable.

Lambdas and LINQ would be overkill for this. You can just do a simple foreach:
string match = "";
foreach (var str in splitChar)
{
if (content.Contains(str))
{
match = str;
break;
}
}
if (!String.IsNullOrEmpty(match))
{
// Do whatever with `match`
}
If you really wanted to use LINQ, though, FirstOrDefault would be your best bet:
string match = splitChar.FirstOrDefault(s => content.Contains(s));
if (!String.IsNullOrEmpty(match))
{
// Do whatever with `match`
}

Have you tried checking with FirstOrDefault like the following?
string[] splitChar = new string[] { "+=", "-=" };
string content = "5+=2";
var stringPresent = splitChar.FirstOrDefault(x=>content.Contains(x));
if(String.IsNullOrEmpty(stringPresent))
Console.WriteLine("Not found");
else
Console.WriteLine(stringPresent);
Check this Example

Related

Regex alternative for extracting numeric and non-numeric strings

Using the below expression, I'm able to get the expected output and extract numbers or string and split to a string array.
Regex _re = new Regex(#"(?<=\D)(?=\d)|(?<=\d)(?=\D)", RegexOptions.Compiled);
_re.Split("2323dfdf233fgfgfg ddfdf334").Dump(); //string can be any alphanumeric start with
How to achieve the same thing without using Regex? Do I need to parse each char and segregate? I have a large array of text which needs to be processed to extract but I cannot use regex as inputs provided.
For a Linq solution, you can combine the use of Enumerable.Skip() and Enumerable.TakeWhile() while checking for char.IsDigit() to determine whether the character is a digit or not. For example:
string inputString = "2323dfdf233fgfgfg ddfdf334";
var list = new List<string>();
int usedLength = 0;
while (usedLength < inputString.Length)
{
bool isDigit = char.IsDigit(inputString[usedLength]);
string item = string.Concat(inputString.Skip(usedLength).
TakeWhile((c) => char.IsDigit(c) == isDigit));
usedLength += item.Length;
list.Add(item);
};
Then you can easily iterate through the list:
foreach (string item in list)
Console.WriteLine(item);
Output:
2323
dfdf
233
fgfgfg ddfdf
334
This solution is fast enough. Check with larger strings.
string str = "2323dfdf233fgfgfg ddfdf334";
var strings = new List<string>();
var sb = new StringBuilder();
var lastCharIsNumber = char.IsDigit(str[0]);
foreach (var c in str) {
if (char.IsDigit(c) ) {
if (!lastCharIsNumber) {
strings.Add(sb.ToString());
sb.Clear();
}
lastCharIsNumber = true;
}
else {
if (lastCharIsNumber) {
strings.Add(sb.ToString());
sb.Clear();
}
lastCharIsNumber = false;
}
sb.Append(c);
}
strings.Add(sb.ToString());
strings.Dump();

Find two strings in list with a regular expression

I need to find two strings within a list that contains the characters from another string, which are not in order. To make it clear, an example could be a list of animals like:
lion
dog
bear
cat
And a given string is: oodilgn.
The answer here would be: lion and dog
Each character from the string will be used only once.
Is there a regular expression that will allow me to do this?
You could try to put the given string between []. These brackets will allow choosing - in any order - from these letters only. This may not be a perfect solution, but it will catch the majority of your list.
For example, you could write oodilgn as [oodilgn], then add a minimum number of letters to be found - let's say 3 - by using the curly brackets {}. The full regex will be like this:
[oodilgn]{3,}
This code basically says: find any word that has three of the letters that are located between brackets in any order.
Demo: https://regex101.com/r/MCWHjQ/2
Here is some example algorithm that does the job. I have assumed that the two strings together don't need to take all letters from the text else i make additional commented check. Also i return first two appropriate answers.
Here is how you call it in the outside function, Main or else:
static void Main(string[] args)
{
var text = "oodilgn";
var listOfWords = new List<string> { "lion", "dog", "bear", "cat" };
ExtractWordsWithSameLetters(text, listOfWords);
}
Here is the function with the algorithm. All string manuplations are entirely with regex.
public static void ExtractWordsWithSameLetters(string text, List<string> listOfWords)
{
string firstWord = null;
string secondWord = null;
for (var i = 0; i < listOfWords.Count - 1; i++)
{
var textCopy = text;
var firstWordIsMatched = true;
foreach (var letter in listOfWords[i])
{
var pattern = $"(.*?)({letter})(.*?)";
var regex = new Regex(pattern);
if (regex.IsMatch(text))
{
textCopy = regex.Replace(textCopy, "$1*$3", 1);
}
else
{
firstWordIsMatched = false;
break;
}
}
if (!firstWordIsMatched)
{
continue;
}
firstWord = listOfWords[i];
for (var j = i + 1; j < listOfWords.Count; j++)
{
var secondWordIsMatched = true;
foreach (var letter in listOfWords[j])
{
var pattern = $"(.*?)({letter})(.*?)";
var regex = new Regex(pattern);
if (regex.IsMatch(text))
{
textCopy = regex.Replace(textCopy, "$1*$3", 1);
}
else
{
secondWordIsMatched = false;
break;
}
}
if (secondWordIsMatched)
{
secondWord = listOfWords[j];
break;
}
}
if (secondWord == null)
{
firstWord = null;
}
else
{
//if (textCopy.ToCharArray().Any(l => l != '*'))
//{
// break;
//}
break;
}
}
if (firstWord != null)
{
Console.WriteLine($"{firstWord} { secondWord}");
}
}
Function is far from optimised but does what you want. If you want to return results, not print them just create an array and stuff firstWord and secondWord in it and have return type string[] or add two paramaters with ref out In those cases you will need to check the result in the calling function.
please try this out
Regex r=new Regex("^[.*oodilgn]$");
var list=new List<String>(){"lion","dog","fish","god"};
var output=list.Where(x=>r.IsMatch(x));
result
output=["lion","dog","god"];

How to find match letter in (mystring after match letter)

I have need to check complex property in c#. I get the complex property List of string are:
EmployeeID
contactNo
Employee.FirstName // these is complex property
Employee.LastName // these is complex property
I know about regex.match() but i have doubt about how to check the string in after placed in dot value that means i want to check in Employee and after placed dot value. can you please help any idea about this?
Using regex, you can match complex properties like this:
List<string> properties = new List<string>()
{
"EmployeeID",
"contactNo",
"Employee.FirstName", // these is complex property
"Employee.LastName", // these is complex property
};
Regex rgx = new Regex(#"Employee\.(.*)");
var results = new List<string>();
foreach(var prop in properties)
{
foreach (var match in rgx.Matches(prop))
{
results.Add(match.ToString());
}
}
If you just want what is after the . (FirstName and LastName), replace the pattern like this:
Regex rgx = new Regex(#"(?<=Employee\.)\w*");
Without regex:
List<string> listofstring = { .... };
List<string> results = new List<string>();
const string toMatch = "Employee.";
foreach (string str in listofstring)
{
if (str.StartsWith(toMatch))
{
results.Add(str.Substring(toMatch.Length));
}
}
If you just need to match .
List<string> listofstring = { .... };
List<string> results = new List<string>();
const string toMatch = ".";
int index = -1;
foreach (string str in listofstring)
{
index = str.IndexOf(toMatch);
if(index >= 0)
{
results.Add(str.Substring(index + 1));
}
}

I want substring from set of string after a pattern exist in c#

I have 3 string ---
m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU
m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER
m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT
and I want R0RKE_52_GU, R10KE_52_TCRER,R0HKE_52_NT.
Note: m60_CLDdet2_LOSS2CLF_060520469434 is varying so I want to find substring if R0RKE or R10KE or R0HKE exists
I would suggest using a Regular expression for this, it is much more versatile for pattern matching.
var matches = System.Text.RegularExpressions.Regex.Matches(text, #"(R0RKE|R10KE|R0HKE).*");
I want to find substring if R0RKE or R10KE or R0HKE exists
This LINQ query returns the desired result:
var strings=new[]{"m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU","m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER","m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT"};
string[] starts = { "R0RKE", "R10KE", "R0HKE" };
var result = strings
.Select(str => new { str, match = starts.FirstOrDefault(s => str.IndexOf("_" + s) >= 0)})
.Where(x => x.match != null)
.Select(x => x.str.Substring(x.str.IndexOf(x.match)));
Console.Write(String.Join(",", result)); // R0RKE_52_GU,R10KE_52_TCRER,R0HKE_52_NT
I write it into static method:
private static string TakeIt(string inputString)
{
if (!Regex.IsMatch(inputString, "(R0RKE|R10KE|R0HKE)"))
{
return string.Empty;
}
var regex = new Regex(#"_");
var occurances = regex.Matches(inputString);
var index = occurances[3].Index + 1;
return inputString.Substring(index, inputString.Length - index);
}
void Main()
{
var string1 = "m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU";
var string2 = "m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER";
var string3 = "m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT";
var string4 = "m60_CLDdet2_LOSS2CLF_060520469434_hhhhh";
Console.WriteLine(TakeIt(string1));
Console.WriteLine(TakeIt(string2));
Console.WriteLine(TakeIt(string3));
Console.WriteLine(TakeIt(string4));
}
Hope this help.
Update: added .Any - it simplifies the code and it's just as same efficient.
If you just need to check for three strings inside string array you can do :
static string[] GetStrings(string[] dirty, string[] lookUpValues)
{
List<string> result = new List<string>();
for (int i = 0; i < dirty.Length; i++) if (lookUpValues.Any(dirty[i].Contains)) result.Add(dirty[i]);
return result.ToArray();
}
Usage: string[] result = GetStrings(dirty, new[] {"R0RKE", "R10KE", "R0HKE"});
Also you can use LINQ query and Regex.Matches as others advised.

How do I check if a string contains a string from an array of strings?

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

Categories