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);
}
}
}
}
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.
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 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 7 years ago.
Improve this question
How to find substring (Ou=9999998 only number) from string?
For example, suppose this is my string:
string myString = "cn=54445sddsfsd,ou=9998fgfgfgf8855,o=fgfgfdg,u=dfddfgfgg,subject=5454gffdgfg454hg";
I want to only 99988855
I suggest converting the string to dictionary with a help of Linq:
using System.Collections.Generic; // for Dictionary
using System.Linq; // Linq: ToDictionary
...
String source =
"cn=54445sddsfsd,ou=99988855,o=fgfgfdg,u=dfddfgfgg.subject=5454gffdgfg454hg";
Dictionary<String, String> data = source
.Split(',')
.ToDictionary(line => line.Substring(0, line.IndexOf('=')),
line => line.Substring(line.IndexOf('=') + 1));
then get the value
// "99988855"; you may want to put int.Parse(data["ou"]); if you want integer value
String result = data["ou"];
or check if there's value and get it if it is:
String result;
if (data.TryGetValue("ou", out result)) {
// "ou" key found
}
else {
// no "ou" key found
}
Try this way you will get all the number part from this string after equal to symbol in an arry.
string myString = "cn=54445sddsfsd,ou=99988855,o=fgfgfdg,u=dfddfgfgg,subject=5454gffdgfg454hg";
string[] myArray= myString.Split(',');
string[] finalOutPut = (from item in myArray
where Regex.IsMatch(item.Substring(item.LastIndexOf('=') + 1), #"^\d+$")
select item.ToString()).ToArray<string>();
In this code the array finalOutput will have one value ie) ou=99988855.
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 7 years ago.
Improve this question
I have files on a local server with the address of \\localServerAddress\Folder\Program.exe. I need to remove the server address dynamically and replace it with a different server address that is being selected elsewhere in the form. The server names can be different lengths, therefore, I can not use the string.Substring function.
So given the input
\\localServerAddress\Folder\Program.exe
I would like the result
\\differentServerAddress\Folder\Program.exe
If you are always working with UNCs
Then
string toRemove = new Uri(yourString).host;
string newString = yourString.Replace(String.format(#"\\{0})",toRemove)
, String.format(#"\\{0})",whateveryouwant));
Use this method:
string changeServerInPathString(string originalString, string newServer)
{
List<string> stringParts = originalString.TrimStart('\\').Split('\\').ToList();
stringParts.RemoveAt(0);
stringParts.Insert(0, newServer);
return string.Join("\\", stringParts.ToArray()).Insert(0, "\\\\");
}
You can use something like this:
void Main()
{
string path = #"\\localServerAddress\Folder\Program.exe";
UriBuilder bld = new UriBuilder(path);
bld.Host = "NewServer";
Console.WriteLine(bld.Uri.LocalPath);
}
Result: \\newserver\Folder\Program.exe
string text = #"\\test\FolderName\foo.exe";
text = text.Replace('\\', '-'); \\ this is done as I was not able to make the regex **\\\\\\(.)*?\\** , work.
Regex rg = new Regex("--.*?-"); \\ if in case the above mentioned regex is made to work correctly please replace the regex with the same.
text = rg.Replace(text, "");
Console.WriteLine(text.Replace('-', '\\'));
Console.Read();
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().