How to get id from String with using Regex - c#

I want to get only number id from string. result : 123456
var text = "http://test/test.aspx?id=123456dfblablalab";
EDIT:
Sorry, Another number can be in the text. I want to get first number after id.
var text = "http://test/test.aspx?id=123456dfbl4564dsf";

Use:
Regex.Match(text, #"id=(\d+)").Groups[1].Value;

It depends on the context - in this case it looks like you are parsing a Uri and a query string:
var text = "http://test/test.aspx?id=123456dfblablalab";
Uri tempUri = new Uri(text);
NameValueCollection query = HttpUtility.ParseQueryString(tempUri.Query);
int number = int.Parse(new string(query["id"].TakeWhile(char.IsNumber).ToArray()));

Someone will give you a C# implementation, but it's along the lines of
/[\?\&]id\=([0-9]+)/
Which will match either &id=123456fkhkghkf or ?id=123456fjgjdfgj (so it'll get the value wherever it is in the URL) and capture the number as a match.

Related

How to remove word from the string in a generic way

I have a string which is basically a url something like APIPAth/resources/customers/SSNNumber/authorizations/contracts.
The SSNNumber can be of any value. Its the actual SSN number which I want to remove from the string and the string should look like APIPAth/resources/customers/authorizations/contracts.
I can't find a proper solution in which without hardcoding the word and removing the string
I tried using Find and Replace but I think the function would require the particular word
Looking at the URL you provided, it appears you only want to get rid of digits. You could accomplish that with this line:
var output = Regex.Replace(input, #"[\d]", string.Empty);
There are many ways to skin this cat depending on what stays static.
One way would be to split the url by separators and join them back
var url = #"APIPAth/resources/customers/SSNNumber/authorizations/contracts";
var items = new List<string>(url.Split('/'));
items.RemoveAt(3);
url = string.Join("/", items);
Another way would be to use Regex
var url = #"APIPAth/resources/customers/SSNNumber/authorizations/contracts";
url = Regex.Replace(url, #"/customers/[^/]+/authorizations/", "/customers/authorizations/")
If you elaborate on what you expect in a generic solution, i.e. what part stays static, then I can help you out better
If SSN in number then it has to have form of this 000 00 0000 means 9 digits consequents.
Took a string parse it by / and you get an array of elements lets say parsed
for(int i=0; i<parsed.length; i++){
if(parsed[i].length === 9){
...keep this i...
}
}
remove this parsed[i] from whole parsed and concat with /

How to get a certain part from an HttpGET request query string

I need to get a certain part from a GET request query string. For example, if the query string is:
action=balance&id=123&session_id=123&key=3843
I would like to convert it to
action=balance&id=123&session_id=123
i.e. I would like to cut off the key parameter part. How could I do that?
After a short googling, I've found the answer here: https://www.codeproject.com/Tips/574956/How-to-get-URL-and-QueryString-value-in-an-ASP-NET
In short, you are able to retrieve what you are looking for by using the following method:
Request.ServerVariables("QUERY_STRING")
use the substring function in your language of choice
for eg. in javascript you can do it as
var f = "action=balance&id=123&session_id=123&key=3843";
var a = f.replace(f.substring(f.indexOf('&key')),"");
There are lot of other ways also.
Try
Regex.Replace(Request.RawUrl, #"&key.*", "")
string qs = Request.params;
This will return collection of all params in curre
Get the Last Index Of char '&'. Then get the substring.
string url = Request.params;
int index = url.LastIndexOf('&');
var urlWithOutKey = url.Substring(0, index);
I have investigated a little bit more and find out this solution
string url = Request.RequestUri.ToString();
Uri uri = new Uri(url);
string urlStringQuery = uri.Query;
int endIndex = urlStringQuery.IndexOf("&key", 1);
string query = urlStringQuery.Substring(1, endIndex - 1);

How to get the string data which is outside of parenthesis in C#

I need to get the data which is outside of parenthesis
string data = "English(Language)";
string result= "English";
The result should display the text "English".
I tried with Regex but not able to get the desired result.
Easiest solution that I can think of:
string data = "English(Language)";
string result = data.Substring(0, data.IndexOf('('));
That is of course, if you never need the data within the parenthesis.
Another way to do it is by using String.Split:
string data = "English(Language)";
string result = data.Split('(')[0];
This is marginally slower than the first example since it needs to allocate memory for an array.
The third way to do it is via regular-expressions:
string data = "English(Language)";
var pattern = new Regex("(\\w+\\s?)\\((\\w+)\\)", RegexOptions.Compiled);
string result = pattern.Match(data).Groups[1].Value;
This is the slowest of all the examples, but captures both "English" and "Language". It also allows for whitespace \s? between English and (Language).
A great tool for testing regular expressions is RegexPal, just remember to escape everything when you move it over to C#.
Here is a fiddle, testing the performance of all options.
Try:
string input = "English(Language)";
string regex = "(\\(.*\\))";
string output = Regex.Replace(input, regex, "");
You will need that:
using System.Text.RegularExpressions;
If you dont bother to use Regex, the below solution works fine.
string data = "English(Language)";
string result = Regex.Match(data, #"(.*)\(.*\)").Groups[1].Value;
Console.WriteLine(result); // English
Hi take a look at the Split methods:
string data = "English(Language)";
string result= "English";
var value = data.Split('(').First();
Console.WriteLine (value);
Result :
English
xd or just:
string data = "English(Language)";
string result = data.Replace("(Language)", "");

How to extract last 5 digits from a link

how do i extract the last 5 digits in C# of a link, for example
www.mywebsite.com?agent_id=12345
now I want to save the 12345 in a session variable
Session["agent_id"] = ???
I think var id = Request["agent_id"] should work.
If you are trying to get the agent_id value from the current request, then Marcos' answer will get you what you want.
However, if the "link" you are referring to is in some other string variable, your best bet is to use regular expressions.
string someUrl = "www.mywebsite.com?agent_id=12345";
var match = Regex.Match(someUrl, "[?&]agent_id=(\d+)";
if (match.Success) {
Session["agent_id"] = match.Groups[1].Value;
}
You can use the query string property for that
string agentId = Request.QueryString["agent_id"];
more info for QueryString here

Fixed string Regular Expression C#

Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());

Categories