This question already has answers here:
How to simplify an if condition having multiple OR cases [closed]
(5 answers)
Closed 6 years ago.
Basically I want to detect more than one string, current code example is
if (!str3.Contains("example1"))
{
continue;
}
How would I add " example1 ", " example2 " & " example3 "
You can use Linq if you want to test with a large list:
var excludes = new[] { "example1", "example2", "example3" };
//your loop here
{
if (!excludes.Any(x => str3.Contains(x)))
{
continue;
}
}
Personally, I prefer the way of looping because it solves the problem of manually expanding your code. For example...
public void MyMethod(string param)
{
var myList = new string[]
{
"example1",
"example2",
"example3"
};
foreach (var item in myList)
{
if (!param.Contains(item)) continue;
}
//Do something here
}
Basically, you're creating a collection of items you want to search for. Using that, you loop through them and compare them against the target string.
I don't know the full scope of the function so I can't exactly add more but this is already pretty basic.
If the strings follow a specific pattern, Regex is always a clean-looking option.
If the strings are "example1", "example2", etc., you could use this regex:
/example[0-9]+/g
Some C# to find the first and second match (source: http://www.dotnetperls.com/regex):
// Get first match.
Match match = Regex.Match(str3, #"example[0-9]+");
if (match.Success)
{
//matched one of the strings
}
// Get second match.
match = match.NextMatch();
if (match.Success)
{
//process second match
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method:
private string RemoveFromList(string sentence)
{
var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" };
var control = lists.Any(sentence.Contains);
string result;
if (control)
{
var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains)
?? throw new InvalidOperationException(), StringComparison.Ordinal);
result = index != -1 ? sentence.Remove(index) : sentence;
}
else
result = sentence;
return result;
}
var str = "ask- This is a sentence.";
Message.Box(RemoveFromList(str));
// It does not give to me: This is a sentence.
This method does not work properly. It does not remove the keyword from the string.
Using string.Replace is the simplest approach:
foreach (var word in lists)
{
sentence = sentence.Replace(word,"").Trim();
}
Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use IndexOf check it's 0 and then take the string starting from word.Length using Substring. Or use StartsWith:
foreach (var word in lists)
{
if (sentence.StartsWith(word))
{
sentence = sentence.Substring(word.Length).Trim();
// break; // if only one
}
}
There are 2 options for you.
First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove.
s.Remove(index, len);
If string contains it than replace the occurrence of keyword with empty string
s.Replace("keyword", "");
Another option is you could create an extension since you already know what items to remove.
using System.Text.RegularExpressions;
public static string RemoveFromList(this string sentence)
{
new List<string>{ "ask-",
"que-",
"(app)",
"(exe)",
"(foo)" }.ForEach(name =>
{
sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " ");
});
return sentence;
}
Useage
var str = "ask- This is (app) a que- sentence.".RemoveFromList();
Note
I used Regex.Replace as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.
This question already has an answer here:
C# Remove a letter that trails a number from multiple instances in a string whether with Regex by another method
(1 answer)
Closed 4 years ago.
Suppose I have a file like this:
EN;05;UK;55;EN;66;US;87;US;89;EN;66;UK;87;
I want remove all the EN occurrence, so the final string should be:
UK;55;US;87;US;89;UK;87;
I can remove the EN using string.Replace("EN", "") but how to remove also the number?
I will propose an alternative not using RegEx. This will work if the number following the abbreviation is more than two characters.
public static string RemoveDataPoints(this string data, string indentifier)
{
var temp = "";
var fields = data.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i=0; i<fields.Length; i=i+2)
{
if (!fields[i].Equals(indentifier))
{
temp += String.Format("{0};{1};", fields[i], fields[i + 1]);
}
}
return temp;
}
Then call:
var output = "EN;05;UK;55;EN;66;US;87;US;89;EN;66;UK;87;".RemoveDataPoints("EN");
You could make use of a regular expression:
string output = Regex.Replace(input, "EN\\;\\d{2}\\;", "");
where input is your string, EN;05;UK;55;EN;66;US;87;US;89;EN;66;UK;87;.
I'm searching for a regex to match all C# methods in a text and the body of each found method (refrenced as "Content") should be accessible via a group.
The C# Regex above only gives the desired result if there exists exactly ONE method in the text.
Source text:
void method1(){
if(a){ exec2(); }
else { exec3(); }
}
void method2(){
if(a){ exec4(); }
else { exec5(); }
}
The regex:
string pattern = "(?:[^{}]|(?<Open>{)|(?<Content-Open>}))+(?(Open)(?!))";
MatchCollection methods = Regex.Matches(source,pattern,RegexOptions.Multiline);
foreach (Match c in methods)
{
string body = c.Groups["Content"].Value; // = if(a){ exec2(); }else { exec3();}
//Edit: get the method name
Match mDef= Regex.Match(c.Value,"void ([\\w]+)");
string name = mDef.Groups[1].Captures[0].Value;
}
If only the method1 is contained in source, it works perfectly, but with additional method2 there is only one Match, and you cannot extract the individual method-body pairs any more.
How to modify the regex to match multiple methods ?
Assuming you only want to match basic code like those samples in your question, you can use
(?<method_name>\w+)\s*\((?s:.*?)\)\s*(?<method_body>\{(?>[^{}]+|\{(?<n>)|}(?<-n>))*(?(n)(?!))})
See demo
To access the values you need, use .Groups["method_name"].Value and .Groups["method_body"].Value.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm creating a software about TV series. I need to get the "episode number" from the filename (a string) of the episode.
Examples of filenames:
"Title of the episode 2x04"
"I am another title S05E22"
"Amazing tv serie 22x2"
I thought about splitting the title part from the episode part, but the format of the filename is not the same everytime (eg. nxmm,SnnEmm, nnxm).
Here's my simple code:
foreach (string filename in path) {
if (filename.Contains(*season n episode m*)) {
// do something
}
}
you should use regex for this:
var list = new List<string>();
list.Add("Lost 04x01");
list.Add("Lost 04x02");
list.Add("Lost 4x3");
list.Add("Lost 4x04");
list.Add("Lost S04E05");
list.Add("Lost S04E6");
Regex regex = new Regex(#"S?\d{1,2}[X|E]?\d{1,2}", RegexOptions.IgnoreCase);
foreach (string file in list) {
if (regex.IsMatch(file))
{
// true
}
}
regex101 Demo
Here is the code
string one = "04x22";
string two = "s04e22";
if ((one.Split('x')).Count == 1)
{
string[] res = (one.Split('e'));
// result is res[1]
}
else
{
string[] res = (one.Split('x'));
// result is res[1]
}
Use a regular expression:
var regex = new Regex(#"(?<season>\d+)[Ex](?<episode>\d+)");
foreach (string file in path) {
var match = regex.Match(file);
if (match.Success) {
Console.WriteLine(match.Groups["season"].Value);
Console.WriteLine(match.Groups["episode"].Value);
}
}
This one will match 04x22, 4x22, S04E22, etc. You should be able to tailor it to be more or less restrictive as you require.
You would need to use a regular expression to find the season and episode number from the filename.
Something like (\d?\d)[xE](\d\d). The first group would be the season number, the second - the episode number. See the regex fiddle on explanation of the regex and a demo.
You would need to use Regex.Match() method in your code instead of Contains().
I have a string that looks like this
2,"E2002084700801601390870F"
3,"E2002084700801601390870F"
1,"E2002084700801601390870F"
4,"E2002084700801601390870F"
3,"E2002084700801601390870F"
This is one whole string, you can imagine it being on one row.
And I want to split this in the way they stand right now like this
2,"E2002084700801601390870F"
I cannot change the way it is formatted. So my best bet is to split at every second quotation mark. But I haven't found any good ways to do this. I've tried this https://stackoverflow.com/a/17892392/2914876 But I only get an error about invalid arguements.
Another issue is that this project is running .NET 2.0 so most LINQ functions aren't available.
Thank you.
Try this
var regEx = new Regex(#"\d+\,"".*?""");
var lines = regex.Matches(txt).OfType<Match>().Select(m => m.Value).ToArray();
Use foreach instead of LINQ Select on .Net 2
Regex regEx = new Regex(#"\d+\,"".*?""");
foreach(Match m in regex.Matches(txt))
{
var curLine = m.Value;
}
I see three possibilities, none of them are particularly exciting.
As #dvnrrs suggests, if there's no comma where you have line-breaks, you should be in great shape. Replace ," with something novel. Replace the remaining "s with what you need. Replace the "something novel" with ," to restore them. This is probably the most solid--it solves the problem without much room for bugs.
Iterate through the string looking for the index of the next " from the previous index, and maintain a state machine to decide whether to manipulate it or not.
Split the string on "s and rejoin them in whatever way works the best for your application.
I realize regular expressions will handle this but here's a pure 2.0 way to handle as well. It's much more readable and maintainable in my humble opinion.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
const string data = #"2,""E2002084700801601390870F""3,""E2002084700801601390870F""1,""E2002084700801601390870F""4,""E2002084700801601390870F""3,""E2002084700801601390870F""";
var parsedData = ParseData(data);
foreach (var parsedDatum in parsedData)
{
Console.WriteLine(parsedDatum);
}
Console.ReadLine();
}
private static IEnumerable<string> ParseData(string data)
{
var results = new List<string>();
var split = data.Split(new [] {'"'}, StringSplitOptions.RemoveEmptyEntries);
if (split.Length % 2 != 0)
{
throw new Exception("Data Formatting Error");
}
for (var index = 0; index < split.Length / 2; index += 2)
{
results.Add(string.Format(#"""{0}""{1}""", split[index], split[index + 1]));
}
return results;
}
}
}