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().
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I face the following problem....
I have for example one of those strings:
string formula1 = "=SUMME(A1:A6)"
string formula2 = "=RUNDEN(SUMME(A6);1)"
string formula3 = "=AUFRUNDEN(ABS(RUNDEN(SUMME(A1:A6);2));2)"
string formula4 = "=AUFRUNDEN(RUNDEN(ABS(RUNDEN(SUMME(A1:A6);2));2);2)"
these are Excel formulas in German language
but I really need the function names to be replaced to function names in English language
I have thought about creating a dictionary, consisting of German function names(Keys)and English function names(Values)
would it be appropriate to find the German function names via regex in order to replace them with English terms later on?
unfortunately my regex knowledge is not really good and it is hard for me to create a regex that would match this pattern. Or would you solve it differently?
hope that is so far understandable. Thx for helping
You can try
(?<name>[A-Za-z][A-Za-z0-9]*)\s*\(
pattern; so function
Must start from A..Z or a..z
Can contain A..Z or a..z or 0..9 charactes
Must end with zero or more whitespaces and (
Code:
private static Dictionary<string, string> subs =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
//TODO: add {Deutsch, English}, pairs here
{ "RUNDEN", "ROUND" },
{ "ABS", "ABS" },
{ "SUMME", "SUM" },
{ "AUFRUNDEN", "ROUNDUP"},
};
private static string ConvertExcel(string formula) {
return Regex.Replace(
formula,
#"(?<name>[A-Za-z][A-Za-z0-9]*)\s*\(",
m => subs.TryGetValue(m.Groups["name"].Value, out var newValue)
? newValue + "("
: m.Value); // do nothing, if translation is not found
}
Demo:
string[] tests = new string[] {
"=SUMME(A1:A6)",
"=RUNDEN(SUMME(A6);1)",
"=AUFRUNDEN(ABS(RUNDEN(SUMME(A1:A6);2));2)",
"=AUFRUNDEN(RUNDEN(ABS(RUNDEN(SUMME(A1:A6);2));2);2)",
};
var result = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-52} <=> {ConvertExcel(test)}"));
Console.Write(result);
Outcome:
=SUMME(A1:A6) <=> =SUM(A1:A6)
=RUNDEN(SUMME(A6);1) <=> =ROUND(SUM(A6);1)
=AUFRUNDEN(ABS(RUNDEN(SUMME(A1:A6);2));2) <=> =ROUNDUP(ABS(ROUND(SUM(A1:A6);2));2)
=AUFRUNDEN(RUNDEN(ABS(RUNDEN(SUMME(A1:A6);2));2);2) <=> =ROUNDUP(ROUND(ABS(ROUND(SUM(A1:A6);2));2);2)
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I have a string "ABD-DDD-RED-Large" and need to extract "DDD-RED"
using the Split I have:
var split = "ABD-DDD-RED-Large".Split('-');
var first = split[0];
var second = split[1];
var third = split[2];
var fourth = split[3];
string value = string.Join("-", second, third);
just wondering if there's a shorter code
If you just want the second and third parts of an always 4 part (delimited by -) string you can one line it with LINQ:
string value = string.Join("-", someInputString.Split('-').Skip(1).Take(2));
An input of: "ABD-DDD-RED-Large" would give you an output of: "DDD-RED"
Not enough information. You mentioned that string is not static. May be Regex?
string input = "ABD-DDD-RED-Large";
string pattern = #"(?i)^[a-z]+-([a-z]+-[a-z]+)";
string s = Regex.Match(input, pattern).Groups[1].Value;
Use regex
var match = Regex.Match(split, #".*?-(.*?-.*?)-.*?");
var value = match.Success ? match.Groups[1].Value : string.Empty;
I'm going out on a limb and assuming your string is always FOUR substrings divided by THREE hyphens. The main benefit of doing it this way is that it only requires the basic String library.
You can use:
int firstDelIndex = input.IndexOf('-');
int lastDelIndex = input.LastIndexOf('-');
int neededLength = lastDelIndex - firstDelIndex - 1;
result = input.Substring((firstDelIndex + 1), neededLength);
This is generic enough to not care what any of the actual inputs are except the hyphen character.
You may want to add a catch at the start of the method using this to ensure there are at least two hyphen's in the input string before trying to pull out the requested substring.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
ok I have no idea on how to do this and i have tried looking up how to do this but nothing good came up so ill ask it here. So what i am trying to do is:
string input = TextEditor.text; <-- this is in windows form application and
The "TextEditor" is the textbox for input
i want to take the string (which is input from the texct box) then split it so each word is on every other line like so:
if input = "hi my name is is"
out put should be:
hi: 1
my: 1
name: 1
is: 2 <-- if the word is said it shouldn't be repeated.
could someone please help me? I am a true newbie and i am completely lost. I don't have any code yet because I DONT KNOW HOW TO DO THIS!
Use Linq GroupBy and Count:
string inputText = "hi my name is is";
var words = inputText.Split(' ').ToList();
var wordGroups = words.GroupBy(w => w).Select(grp => new {
Word = grp.Key,
Count = grp.Count()
});
string outputText = string.Join("\n", wordGroups.Select(g => string.Format("{0}:\t{1}", g.Word, g.Count)));
/*
hi: 1
my: 1
name: 1
is: 2
*/
Split the input string into an array, then use that to build a dictionary. If the word is already in the dictionary, increment it. Otherwise add it with an initial value of 1.
string input = TextEditor.text;
string[] inputWords = input.Split(' ');
Dictionary<string, int> wordCounts = new Dictionary<string, int>();
foreach (string word in inputWords)
{
if (wordCounts.ContainsKey(word))
{
wordCounts[word]++;
}
else
{
wordCounts.Add(word, 1);
}
}
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
Hi I am facing problem to get specific string. The string as below:
string myPurseBalance = "Purse Balance: +0000004000 556080";
I want to get 4000 out only.
if your string format/pattern is fix then you can get specific value
string myPurseBalance = "Purse Balance: +0000004000 556080";
//
var newPursebal =Convert.ToDouble(myPurseBalance.Split('+')[1].Split(' ')[0]);
You can use this regular expression:
string extract = Regex.Replace(myPurseBalance, #"(.*?)\: \+[0]*(?<val>\d+) (.*)", "${val}")
It searches for the decimals after :, trims the leading 0s and removes everything after the last whitespace.
You can use string.Split to get the +0000004000 and then use string.Substring to get the last four characters by passing the Length-4 as starting index.
string str = myPurseBalance.Split(' ')[2];
str = str.Substring(str.Length-4);
Learn Regex . Here is just simple tutorial
using System;
using System.Text.RegularExpressions;
namespace regex
{
class MainClass
{
public static void Main (string[] args)
{
string input = "Purse Balance: +0000504000 556080";
// Here we call Regex.Match.
Match match = Regex.Match(input, #"\+[0]*(\d+)",
RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
}
}
}