I have a string
string name = \"AL QADEER UR AL REHMAN AL KHALIL UN\";
How would I remove all characters AL
, UR
,
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";
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));
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
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
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 + " ";