I have a string that I need to separate the product ID from, is this format
shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==
I need to get 556 out of there, and in the case of say 2658 etc also possible.
First index ":" I think
str.Substring(str.LastIndexOf(':') + 1);
But then I dont know how to just break after the match, regex better? any help apprecaited
EDIT
These do the exact same thing, seperating the first numbers out
LINQ:
var test = new string(str.Substring(str.IndexOfAny("0123456789".ToCharArray())).TakeWhile(char.IsDigit).ToArray());
Reggex:
var test = Regex.Match(str, #"\d+").Value;
So bears the question, which is better approach?
If the string format is fixed, use the Split function
string str = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
int id = Convert.ToInt32(str.Split(':')[2]);
Console.WriteLine(id);
I'd probably use Regex:
var id = Regex.Match(input, #"\?id:(?<x>\d+)").Groups["x"].Value
Decoded, that Regex means "literally match ?id: then start a capturing group called x and capture one or more digits into it"
The returned Match will have a Groups property that we index by x and retrieve the value
If you want it as an int you can int.Parse the result-you won't need a TryParse because the Regex will have only matched digits
If the format of the string is fixed then this would work:
input[9..input.IndexOf(':',10)];
And it would be more performant than Regex or Split
If you wanted a substring that works with a format change, perhaps:
var x = input.IndexOf("?id:") + 4;
var id = input[x..input.IndexOf(':',x+1)];
This will work even if the order of items changes.
string original = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
string startWithId = original.Substring(original.IndexOf("id:") + 3);
string onlyId = startWithId.Split(':')[0];
Console.WriteLine(onlyId);
Related
string temp = "12345&refere?X=Assess9677125?Folder_id=35478";
I need to extract the number 12345 alone and I don't need the numbers 9677125 and 35478.
What regex can I use?
Here is the regex for extracting 5 digit number in the beginning of the string:
^(\d{5})&
If length is arbitrary:
^(\d+)&
If termination pattern is not always &:
^(\d+)[^\d]
Based on the Sayse's comment you can simply rewrite as:
^(\d+)
and in case of the termination is some number(for instance 999) then:
^(\d+)999
You don't need regex if you only want to extract the first number:
string temp = "12345&refere?X=Assess9677125?Folder_id=35478";
int first = Int32.Parse(String.Join("", temp.TakeWhile(c => Char.IsDigit(c))));
Console.WriteLine(first); // 12345
If the number you want is always at the beginning of the string and terminated by an ampersand (&) you don't need a regex at all. Just split the string on the ampersand and get the first element of the resulting array:
String temp = "12345&refere?X=Assess9677125?Folder_id=35478";
var splitArray = String.Split('&', temp);
var number = splitArray[0]; // returns 12345
Alternatively, you can get the index of the ampersand and substring up to that point:
String temp = "12345&refere?X=Assess9677125?Folder_id=35478";
var ampersandIndex = temp.IndexOf("&");
var number = temp.SubString(0, ampersandIndex); // returns 12345
From what you haven given us this is fairly simple:
var regex = new Regex(#"^(?<number>\d+)&");
var match = regex.Match("12345&refere?X=Assess9677125?Folder_id=35478");
if (match.Success)
{
var number = int.Parse(match.Groups["number"].Value);
}
Edit: Of course you can replace the argument of new Regex with any of the combinations Giorgi has given.
I've Table URL and I'd like select Table Name only. What is the best approach to achieve it?
URLs:
"db://SQL Table.Table.[dbo].[DirectoryType]"
"db://SQL Table.Table.[dbo].[IX_AnalysisResult_ConceptVariations]"
"db://SQL Table.Table.[dbo].[IX_AnalysisResult_DocXConcepts]"
DESIRED OUTPUT:
DirectoryType
IX_AnalysisResult_ConceptVariations
IX_AnalysisResult_DocXConcepts
NOTE: These URLs will have db://SQL Table.Table.[dbo]. in common most of the time so I am using following code to achieve this:
CODE:
var trimURL = tableURL.Replace("db://SQL Table.Table.[dbo].", String.Empty).Replace("[",String.Empty).Replace("]",String.Empty);
OUTPUT:
DirectoryType
IX_AnalysisResult_ConceptVariations
IX_AnalysisResult_DocXConcepts
If for some reason URL prefix is changed then my code won't work. So what is the best way to get a table name from these type of URLs?
You could get the last index of '[' and ']' and get the substring therein:
var startIndex = tableUrl.LastIndexOf('[') + 1; // +1 to start after opening bracket
var endIndex = tableUrl.LastIndexOf(']');
var charsToRead = (startIndex - endIndex) - 1; // -1 to stop before closing bracket
var tableName = tableUrl.Substring( startIndex, charsToRead );
Of course, this assumes you can guarantee no brackets in your table name.
References:
String.Substring
String.LastIndexOf
You can use this regex to match the last thing inside the last group of [] that appears immediately at the end of a string:
\[([^\[^\]]*)\]$
At input db://SQL Table.Table.[dbo].[DirectoryType] you grab the string DirectoryType.
The $ symbol means the end of a string.
You can see it in action here.
An example:
var match = new System.Text.RegularExpressions.Regex(#"\[([^\[^\]]*)\]$", RegexOptions.Singleline);
Match match_result = match.Match("db://SQL Table.Table.[dbo].[DirectoryType]");
string result = "";
if (match_result.Groups.Count > 1)
result = match_result.Groups[1].Value;
//result = "DirectoryType"
Remember using System.Text.RegularExpressions;
var matcher = new System.Text.RegularExpressions.Regex(#"^.*\[(?<table>.*?)\]""$", RegexOptions.Compiled);
var results = matcher.Match(/*your input string*/);
Inspect the results in the debugger and you'll find how to extract what you are looking for.
Note that this pattern assumes that your data actually includes the quotation marks shown in your question.
you were doing it right, i just used split on '.', I am assuming your url contains minimum anything.[DirectoryType]"
string op = tableURL.Split('.')[tableURL.Split('.').Length - 1].Replace("[", "").Replace("]", "");
I have a string as following 2 - 5 now I want to get the number 5 with Regex C# (I'm new to Regex), could you suggest me an idea? Thanks
You can use String.Split method simply:
int number = int.Parse("2 - 5".Split('-', ' ').Last());
This will work if there is no space after the last number.If that is the case then:
int number = int.Parse("2 - 5 ".Split('-', ' ')
.Last(x => x.Any() && x.All(char.IsDigit)));
Very simply as follows:
'\s-\s(\d)'
and extract first matching group
#SShashank has the right of it, but I thought I'd supply some code, since you mentioned you were new to Regex:
string s = "something 2-5 another";
Regex rx = new Regex(#"-(\d)");
if (rx.IsMatch(s))
{
Match m = rx.Match(s);
System.Console.WriteLine("First match: " + m.Groups[1].Value);
}
Groups[0] is the entire match and Groups[1] is the first matched group (stuff in parens).
If you really want to use regex, you can simply do:
string text = "2 - 5";
string found = Regex.Match(text, #"\d+", RegexOptions.RightToLeft).Value;
I have the following string:
String myNarrative = "ID: 4393433 This is the best narration";
I want to split this into 2 strings;
myId = "ID: 4393433";
myDesc = "This is the best narration";
How do I do this in Regex.Split()?
Thanks for your help.
If it is a fixed format as shown, use Regex.Match with Capturing Groups (see Matched Subexpressions). Split is useful for dividing up a repeating sequence with unbound multiplicity; the input does not represent such a sequence but rather a fixed set of fields/values.
var m = Regex.Match(inp, #"ID:\s+(\d+)\s+(.*)\s+");
if (m.Success) {
var number = m.Groups[1].Value;
var rest = m.Groups[2].Value;
} else {
// Failed to match.
}
Alternatively, one could use Named Groups and have a read through the Regular Expression Language quick-reference.
I have a string of type "24;#usernamehere,#AWRFR\user,#,#,#usernamehere"
I want to split this string on the first appearance on # and , i.e i want a string to be fetched which is inbetween these two characters.
So for the above string i want the OUTPUT as:
usernamehere
How can i split a string in between two characters using Regex function?
A simple Regex Pattern might do the job:
var pattern = new System.Text.RegularExpressions.Regex("#(?<name>.+?),");
test:
string s = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
pattern.Match(s).Groups["name"].Value; //usernamehere
Using Linq:
using System.Linq;
var input = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
You can split it with a single line:
var x = input.Split('#').Where(e => e.Contains(',')).Select(e => e.Split(',').First());
which is the same as:
var x = from e in input.Split('#')
where e.Contains(',')
select e.Split(',').First();
in both cases the result would be:
x = {"usernamehere", "AWRFR\user", "", ""}
Which is exactly an array with all substrings enclosed by # and ,.
Then if you want the first element just add .First() or do:
x.First();
You need to find the first index of '#' & ','. Then use substring method to get your required trimmed string. Read this for more details on substring method
string s = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string finalString = s.Substring(s.IndexOf('#') + 1, s.IndexOf(',') - s.IndexOf('#') - 1);
Not exactly the way you asked for it, but should do what you want...
string input = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string username = input.Substring(input.LastIndexOf("#") + 1);
If you wanted you could get the position of the first # and the ,
int hashPosition = input.IndexOf("#") + 1;
int commaPosition = input.IndexOf(",");
string username = input.Substring(hashPosition, commaPosition - hashPosition));