extract numerical values from string after dash (-) - c#

I have string value like this Rs.100 - Rs.250 Now I want only 250 from this string.
I tried this but it's not getting output
var result = str.Substring(str.LastIndexOf('-') + 1);
UPDATE
string result = price.Text;
string[] final_result = result.Split('.');
dynamic get_result = final_result(1).ToString();
price.Text = final_result.ToString;

Try this code after getting the result of Rs.250.
var data = Regex.Match(result, #"\d+").Value;

Do it like this:
string str = "Rs.100-Rs.250";
var result = str.Substring(str.LastIndexOf('-') + 1);
String[] final_result = result.Split('.');
var get_result = final_result[1].ToString();
this will get 250 as you wanted.

try this
var result = ("Rs.100 - Rs.250").Split('-').LastOrDefault().Split('.').LastOrDefault();

Related

String Manipulation and splitting string

string url = "test:app:https://test#hotmail.co.uk:Test
I need to split this up to display as follows
string first = "app";
string second = "https://test#hotmail.co.uk:Test";
i have tried the following but falls over on the last colon.
string remove= "";
remove= url.Replace("test:", "");
string first= remove.Substring(remove.LastIndexOf(':') + 1);
string second= remove.Substring(0, remove.IndexOf(':'));
Doing this i get
first = "app";
second = "Test";
When i need
first = "app";
second = "https://test#hotmail.co.uk:Test";
Your use of LastIndexOf is just a bit wonky.
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = url.Replace("test:", "");
string first = remove.Substring(0, remove.IndexOf(":"));
string second = remove.Substring(remove.IndexOf(first) + first.Length + 1);
First grab the app, and we can use the location of app to derive the rest of the string. Because the last index of : would be the one in :Test. We don't want the last index of :. Instead we just want whatever comes after app.
As everything is prefixed with test: you can use a starting position after that and then split after the first occurrance of the : character.
const int IndexOfPrefix = 5; // start position after "test:"
string url = "test:app:https://test#hotmail.co.uk:Test";
var indexOfApp = url.IndexOf(':', IndexOfPrefix);
var part1 = url.Substring(IndexOfPrefix, indexOfApp - IndexOfPrefix);
var part2 = url.Substring(indexOfApp + 1);
Console.WriteLine(part1);
Console.WriteLine(part2);
Something like this should do the trick:
public void ManipulateStrings()
{
string url = "test:app:https://test#hotmail.co.uk:Test";
url = url.Replace("test:", "");
string first = url.Substring(0, url.IndexOf(':'));
string second = url.Substring(url.IndexOf(':') + 1);
}
This basically removed test: from your string, then assigns first and second their values without creating string remove = "" for no reason.
You can use Split(Char[], Int32) to get the desired number of elements (3 : the first unwanted part, the first expected part and the remaining) along with Skip() to remove the unwanted one :
string url = "test:app:https://test#hotmail.co.uk:Test";
var splitted = url.Split(new [] { ':' }, 3).Skip(1).ToArray();
var first = splitted[0];
var second = splitted[1];
Console.WriteLine(first);
Console.WriteLine(second);
This outputs
app
https://test#hotmail.co.uk:Test
Another way to do that is using regular expressions :
The pattern :(?<first>.*?):(?<second>.*) will :
: search for the characters :
(?<first>.*?) creates a group named first that will match any number of any character (lazy)
: search for the characters :
(?<second>.*) creates a group named second that will match any number of any character (greedy)
In example :
string url = "test:app:https://test#hotmail.co.uk:Test";
var pattern = ":(?<first>.*?):(?<second>.*)";
var regex = new Regex(pattern); // using System.Text.RegularExpressions;
Match match = regex.Match(url);
if (match.Success)
{
var first = match.Groups["first"].Value;
var second = match.Groups["second"].Value;
Console.WriteLine(first);
Console.WriteLine(second);
}
This outputs
app
https://test#hotmail.co.uk:Test
you need to change the variable with name "first" to "second" and to change the variable with name "second" to "first"
This is your code:
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = "";
remove = url.Replace("test:", "");
string second = remove.Substring(0, remove.IndexOf(':'));
string first = remove.Substring(remove.IndexOf(":") + 1);
and this is the correct code:
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = "";
remove = url.Replace("test:", "");
string first = remove.Substring(0, remove.IndexOf(':'));
string second = remove.Substring(remove.IndexOf(":") + 1);

dynamic substring in c#

I have a set of code in c# I want to store into the database what the user is entering in the textbox.
The user enters into the textbox like this
input namexyzpan9837663placeofbirthmumbailocationwadala
This is what user enters
(name: xyz pan: 9837663 place of birth: mumbai location: wadala)
Output into the database
xyz 9837663 mumbai wadala
OR
name xyzapan72placeofbirthgoalocationpanji
(> name: xyza pan: 72 place of birth: goa location: panji)
Output into the database
xyza 72 goa panji
name, age, location and placeofbirth are static but the value inside
them are dynamic
I know substring is helpfull but i don't know how to use it.
Use can use Split if the keywords are static :
string strMain = "namexyzpan9837663placeofbirthmumbailocationwadala";
var results = strMain.Split(new string[] { "name", "pan", "placeofbirth", "location" }, StringSplitOptions.RemoveEmptyEntries);
string name = results[0];
string pan = results[1];
string location = results[2];
You said you didn't know how to use Substring, well here it is working:
Note that the second parameter for this method is the length of the string to be taken and not the index at which to stop.
string strMain = "namexyzpan9837663placeofbirthmumbailocationwadala";
int indexOfName = strMain.IndexOf("name");
int indexOfPan = strMain.IndexOf("pan");
int indexOfBirth = strMain.IndexOf("placeofbirth");
int indexOflocation = strMain.IndexOf("location");
int effectiveIndexOfName = indexOfName + "name".Length;
int effectiveIndexOfPan = indexOfPan + "pan".Length;
int effectiveIndexOfBirth = indexOfBirth + "placeofbirth".Length;
int effectiveIndexOflocation = indexOflocation + "location".Length;
string name1 = strMain.Substring(effectiveIndexOfName, indexOfPan- effectiveIndexOfName);
string pan1 = strMain.Substring(effectiveIndexOfPan, indexOfBirth - effectiveIndexOfPan);
string birth1 = strMain.Substring(effectiveIndexOfBirth, indexOflocation - effectiveIndexOfBirth);
string location1 = strMain.Substring(effectiveIndexOflocation);
namenamepan9837663placeofbirthmumbailocationwadala works using the second method. But namepanpan9837663placeofbirthmumbailocationwadala is an interesting case that definitely needs a workaround.
Regex is designed for such case.
var input = #"namexyzpan9837663placeofbirthmumbailocationwadala";
var match = Regex.Match(input, #"^\s*"
+ #"name\s*(?<name>\w+?)\s*"
+ #"pan\s*(?<pan>\w+?)\s*"
+ #"placeofbirth\s*(?<placeOfBirth>\w+?)\s*"
+ #"location\s*(?<location>\w+)\s*" + #"$");
var name = match.Groups["name"].Value;
var pan = match.Groups["pan"].Value;
var placeOfBirth = match.Groups["placeOfBirth"].Value;
var location = match.Groups["location"].Value;

Regex, Remove function in a string

I'm trying to get the function DoDialogwizardWithArguments that is inside a string using Regex:
string:
var a = 1 + 2;DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false);p = q.getBOdy();
actual Regex (pattern):
DoDialogWizardWithArguments\((.*\$?)\)
Result expected:
DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false)
The problem:
If there's another parentheses ")" that is not the parentheses of DoDialogWizardWithArguments function the Regex is getting this too.
How can i get only the function with his open and close parentheses.
If Regex is not possible, whats the better option?
Example regex link:https://regex101.com/r/kP2bQ4/1
Try this one as regex: https://regex101.com/r/kP2bQ4/2
DoDialogWizardWithArguments\(((?:[^()]|\((?1)\))*+)\)
I'd probably try to simplify it like this:
var str = #"var a = 1 + 2;DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false);p = q.getBOdy();"
var lines = str.Split(';');
foreach(var line in lines)
{
if(line.Contains("DoDialogWizardWithArguments")){
int startPos = line.IndexOf("(");
int endPos = line.IndexOf(")");
return line.Substring(startPos+1, endPos - startPos - 1);
}
}
return "Not found";
If you don't want to detect if DoDialogWizardWithArguments was correctly written but just the function itself, try with "DoDialogWizardWithArguments([^,],[^,],[^,],([^,]),.+);".
Example:
String src = #"xdasadsdDoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function(" + "\""
+ "if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"
+ "\"" + "), false);p"; //An example of what you asked for
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(#"DoDialogWizardWithArguments([^,]*,[^,]*,[^,]*,([^,]*),.+);"); //This is your function
MessageBox.Show(r.Match(src).Value);
if (r.IsMatch(src))
MessageBox.Show("Yeah, it's DoDialog");
else MessageBox.Show("Nope, Nope, Nope");

Replace string after at with another string

I have two strings.
First string:
"31882757623"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738
Second string:vandrielfinance.nl
I want to replace asklync.nl to vandrielfinance.nl in the first string after the # with the second string (vandrielfinance.nl). Everything else will stay the same.
So the new string will be:
"31882757623"<sip:+31882757623#vandrielfinance.nl;user=phone>;epid=5440626C04;tag=daa784a738
Here is what I have so far:
static string ReplaceSuffix(string orginal, string newString)
{
string TobeObserved = "#";
orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
string pattern = second.Substring(0, second.LastIndexOf("#") + 1);
string code = orginal.Substring(orginal.IndexOf(TobeObserved) + TobeObserved.Length);
//newString = Regex.Replace(code,second, pattern);
newString = Regex.Replace(second, orginal, pattern);
string hallo = orginal.Replace(newString, second);
Console.Write("Original String: {0}", orginal);
Console.Write("\nReplacement String: \n{0}", newString);
Console.WriteLine("\n" + code);
return newString;
}
why not string.Replace?
string s = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string t = "vandrielfinance.nl";
string u = s.Replace("asklync.nl", t);
Console.WriteLine(u);
I'm not really a fan a string.Split(), but it made for quick work in this case:
static string ReplaceSuffix(string orginal, string newString)
{
var segments = original.Split(";".ToCharArray());
var segments2 = segments[0].Split("#".ToCharArray());
segments2[1] = newString;
segments[0] = string.Join("#", segments2);
var result = string.Join(";", segments);
Console.WriteLine("Original String:\n{0}\nReplacement String:\n{1}, original, result);
return result;
}
If the original domain will really always be asklync.nl, you may even be able to just do this:
static string ReplaceSuffix(string orginal)
{
var oldDomain = "asklync.nl";
var newDomain = "vandrielfinance.nl";
var result = original.Replace(oldDomain, newDomain);
Console.WriteLine("Original String:\n{0}\nReplacement String:\n{1}, original, result);
return result;
}
This should work
var orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
var returnValue = string.Empty;
var split = orginal.Split('#');
if (split.Length > 0)
{
var findFirstSemi = split[1].IndexOf(";");
var restOfString = split[1].Substring(findFirstSemi, split[1].Length - findFirstSemi);
returnValue = split[0] + "#" + second + restOfString;
}
Console.WriteLine("Original String:");
Console.WriteLine("{0}", orginal);
Console.WriteLine("Replacement String:");
Console.WriteLine("{0}", returnValue);
//return returnValue;
I'm not a huge fan of RegEx or string.Split, especially when a string function already exists to replace a portion of a string.
string orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
int start = orginal .IndexOf("#");
int end = orginal .IndexOf(";", start);
string newString = orginal .Replace(orginal.Substring(start, end-start), second );
Console.WriteLine(orginal );
Console.WriteLine(newString);

Grab a part of text when it matches, get rid of the rest because it's useless

I have a text called
string path = "Default/abc/cde/css/";
I want to compare a text.
string compare = "abc";
I want a result
string result = "Default/abc";
The rest of the path /cde/css is useless.Is it possible to grab the desire result in asp.net c#. Thanks.
Is this what you looking for?:
string result = path.Substring(0, path.IndexOf(compare)+compare.Length);
Try this. This will loop through the different levels (assuming these are directory levels) until it matches the compare, and then exit the loop. This means that if there is a folder called abcd, this won't end the loop.
string path = "Default/abc/cde/css";
string compare = "abc";
string result = string.Empty;
foreach (string lvl in path.Split("/")) {
result += lvl + "/";
if (lvl == compare)
{
break;
}
}
if (result.Length>0)
{
result = result.substring(0, result.length-1);
}
string path = "Default/abc/cde/css/";
string answer = "";
string compare = "abc";
if (path.Contains(compare ))
{
answer = path.Substring(0, path.IndexOf(stringToMatch) + compare.Length);
}
Something like the above should work.
I suggest that if you meet questions of this kind in the future, you should try it yourself first.
string result = path.Contains(compare) ? path.Substring(0, (path.IndexOf(compare) + compare.Length)) : path;

Categories