Insert string in regex search C# - c#

How I can write this:
List<string> Words= new List<string>();
Regex re = new Regex(#"\b" + Words[n] + "\b");
My exactly question is how I can search elements from list or string using regex?

Possible Solution:
string testString = "cat and dog";
string[] Words = { "cat", "dog" };
foreach(string word in Words)
{
bool contains = Regex.IsMatch(testString, "\\b" + word + "\\b");
}

You can use all words in one regex:
var words= new List<string>();
var regex = new Regex(string.Format(#"\b(?:{0})\b", string.Join("|", words)), RegexOptions.Compiled);

This will give you a list of string regex patterns:
List<string> words= new List<string>() { "cat", "dog" };
List<string> regexPatterns = words.Select(str => "\\b" + str + "\\b").ToList();
Or if you want a list of Regex objects:
List<Regex> regexObjects = words.Select(str => new Regex("\\b" + str + "\\b")).ToList();

Related

Removing word or character from string followed by space or before space in c#

I have a string
string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
How would I remove all characters AL, UR, UN or may be some more like that.
My string should look like this;
QADEER REHMAN KHALIL
Currently I am trying do like this;
List<string> list = new List<string> { "AL", "UR", "UN" };
foreach (var item in list )
{
systemName = systemName.Replace(item, "");
}
This is also removing AL from KHALIL, how do I restrict this to not removing a word containg that characters.
Update:
While adding spaces to words in List, will only remove words which has space before and after the word. and concatenate UR to following word.
I am loading List of words which are to be removed from database;
Try this please :
var name = "AL QADEER UR AL REHMAN AL KHALIL UN";
var list = new List<string> { "AL", "UR", "UN" };
name = string.Join(" ", name.Split(' ').ToList().Except(list));
static void TestRegex()
{
string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
// Add other strings you want to remove
string pattern = #"\b(AL|UR|UN)\b";
name = Regex.Replace(name, pattern, String.Empty);
// Remove extra spaces
name = Regex.Replace(name, #"\s{2,}", " ").Trim();
Console.WriteLine(name);
}
UPDATE
You can generate the pattern this way:
// Generate pattern
var list = new List<string> { "AL", "UR", "UN" };
string pattern = #"\b(" + String.Join("|", list) + #")\b";
var words = new[] { "AL", "UR", "UN" };
var arr = systemName.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Except(words);
systemName = string.Join(" ", arr);
No need to use regular expressions. Having defined list with "prohibited" words, it's enough to iterate over wprds in the sentence to filter, if word is in the list of prohibited words, then exclude it, otherwise, include the word in final string.
Try this:
string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
string systemName = "";
List<string> list = new List<string> { "AL", "UR", "UN" };
foreach (var item in name.Split(new char[] { ' ', ',', '.' }, StringSplitOptions.RemoveEmptyEntries))
systemName += list.Contains(item) ? "" : item + " ";
I am loading that list from database, and can be change any time, how do use this in regex when changes occur
okay then, the length would always be 2?
no, but not be greater than 4
public static void Main()
{
var input = "AL QADEER UR AL REHMAN AL KHALIL UN AAA BBB";
Regex re = new Regex(#"\b\w{1,4}\b");
var result = re.Replace(input, "");
Console.WriteLine(result);
}
OUTPUT:
QADEER REHMAN KHALIL
dotNetFiddle
Pure LINQ answer with the help of EXCEPT
string name = "AL QADEER UR AL REHMAN AL KHALIL UN";
var list = new string[] { "AL", "UR", "UN" };
name = name
.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
.Except(list)
.Aggregate((prev, next) => $"{prev} {next}");
OUTPUT: QADEER REHMAN KHALIL

Adding chars before and after each word in a string

Imagine we have a string as :
String mystring = "A,B,C,D";
I would like to add an apostrophe before and after each word in my string.Such as:
"'A','B','C','D'"
How can i achieve that?
What's your definition of a word? Anything between commas?
First get the words:
var words = mystring.Split(',');
Then add the apostrophes:
words = words.Select(w => String.Format("'{0}'", w));
And turn them back into one string:
var mynewstring = String.Join(",", words);
mystring = "'" + mystring.replace(",", "','") + "'";
I would let each "word" be determined by the regex \b word boundary. So, you have:
var output = Regex.Replace("A,B,C,D", #"(\b)", #"'$1");
string str = "a,b,c,d";
string.Format("'{0}'", str.Replace(",", "','"));
or
string str = "a,b,c,d";
StringBuilder sb = new StringBuilder(str.Length * 2 + 2);
foreach (var c in str.ToCharArray())
{
sb.AppendFormat((c == ',' ? "{0}" : "'{0}'"), c);
}
str = sb.ToString();
string mystring = "A,B,C,D";
string[] array = mystring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string newstring = "";
foreach (var item in array)
{
newstring += "'" + item + "',";
}
newstring = newstring.Remove(newstring.Length - 1);
Console.WriteLine(newstring);
Output will be;
'A','B','C','D'
Here a DEMO.
Or more simple;
string mystring = "A,B,C,D";
Console.WriteLine(string.Format("'{0}'", mystring.Replace(",", "','")));
you can use regular expressions to solve this problem
like this:
string words= "A,B,C,D";Regex reg = new Regex(#"(\w+)");words = reg.Replace(words, match=> { return string.Format("'{0}'", match.Groups[1].Value); });

Algorithm for filtering top-level directories among a list of paths, C#

Input:
/dir1
/dir1/subdir
/dir1/subdir/sub-subdir
/dir2
Output should be:
/dir1
/dir2
How about this:
string inputDir = "/dir1/subdir/sub-subdir";
string [] Split = inputDir.Split(new Char [] {'/'}, StringSplitOptions.RemoveEmptyEntries);
string outputDir = Split[0];
List<string> result= new List<string>();
foreach (string i in input)
{
string[] tmp = i.split(#"/");
result.add(#"/" + tmp[0]);
}

Extract all strings between [ text1 ] [text2] tags

I have an sql text that includes
"Select * from Table Where [PARAM1] = [PARAM2] ..."
I want to get list between "[" "]" tags to list.
How can I do it ?
You can do it using LINQ
string str = "Select * from Table Where [PARAM1] = [PARAM2] ...";
string[] Array = str.Split().Where(r=> r.StartsWith("[") && r.EndsWith("]"))
.Select(r=> r.Trim('[',']'))
.ToArray();
Use this snippet
string strRegex = #"\[(.*?)\]";
RegexOptions myRegexOptions = RegexOptions.IgnoreCase;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = #"Select * from Table Where [PARAM1] = [PARAM2] ...";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
// myMatch.Groups[0] - your string
}
You can try using regular expressions and some LINQ:
Regex t = new Regex(#"\[([^]]*)\]");
List<String> parameters = t.Matches(input_string).Cast<Match>().Select(a => a.Groups[1].ToString()).ToList();
This will result in a List holding the two matches PARAM1 and PARAM2
You can also do
List<string> matches=Regex.Matches(#"(?<=\[)[^\[\]]*(?=\])")
.Cast<Match>()
.Select(x=>x.Value)
.ToList();
Here is what you need:
Regex t = new Regex(#"\[(.*?)\]");
string str = #"Select * from Table Where [PARAM1] = [PARAM2] ...";
foreach (Match myMatch in myRegex.Matches(str))
{
// myMatch.Groups[0] and so on....
}
Live Demo
To convert a MatchCollection to List use:
List<Match> myMatches = Regex.Matches("bla", #"\[[^]]*)\]").Cast<Match>.toList();
You can try using this regular expression:
Regex regex = new Regex(#"\[.*?\]");
var parameters = regex.Matches(sqlQueryString);

formatting string in C#

How can I convert this list of strings to comma separated value enclosed within quotes without any escape characters?
{"apple", "berry", "cherry"} => well, ""apple", "berry", "cherry""
If I understood you correctly,
"\"" + String.Join("\", \"", new string[]{"apple","berry","cherry"}) + "\"";
or, alternatively,
String.Format("\"{0}\"", String.Join("\", \"", new string[] {"apple","berry","cherry"}));
Read more on System.String.Join(...).
Hope this will do the job
var ar = new []{ "apple", "berry", "cherry" };
var separator = "\",\"";
var enclosingTag = "\"";
Console.WriteLine ( enclosingTag + String.Join(separator, ar) + enclosingTag );
If you are using C#:
using System;
string[] arr = new string[] { "apple", "berry", "cherry" };
string sep = "\",\"";
string enclosure = "\"";
string result = enclosure + String.Join(sep, arr) + enclosure;

Categories