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));
Related
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);
How can I split a C# string based on the first occurrence of the specified character?
Suppose I have a string with value:
101,a,b,c,d
I want to split it as
101
a,b,c,d
That is by the first occurrence of comma character.
You can specify how many substrings to return using string.Split:
var pieces = myString.Split(new[] { ',' }, 2);
Returns:
101
a,b,c,d
string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first = s.Substring(0, index);
string second = s.Substring(index + 1);
You can use Substring to get both parts separately.
First, you use IndexOf to get the position of the first comma, then you split it :
string input = "101,a,b,c,d";
int firstCommaIndex = input.IndexOf(',');
string firstPart = input.Substring(0, firstCommaIndex); //101
string secondPart = input.Substring(firstCommaIndex + 1); //a,b,c,d
On the second part, the +1 is to avoid including the comma.
Use string.Split() function. It takes the max. number of chunks it will create. Say you have a string "abc,def,ghi" and you call Split() on it with count parameter set to 2, it will create two chunks "abc" and "def,ghi". Make sure you call it like string.Split(new[] {','}, 2), so the C# doesn't confuse it with the other overload.
var pieces = myString.Split(',', 2);
This won't work. The overload will not match and the compiler will reject it.
So it Must be:
char[] chDelimiter = {','};
var pieces = myString.Split(chDelimiter, 2);
In .net Core you can use the following;
var pieces = myString.Split(',', 2);
Returns:
101
a,b,c,d
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.
This is probably a super easy question but I can't seem to figure it out. Do you know how to extract just the portion after the '/' in a string. So for like the following:
[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]
So I just want the 'OrderConfirmation_SynergyWorldInc' portion. I got 271 entries where I gotta extract just the end portion (the all have the portions before that in all of them, if that helps).
Thanks!!
IF YOU HAVE A SINGLE ENTRY...
You need to use LastIndexOf with Substring after a bit of trimming:
var s = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
s = s.Trim('[',']');
Console.Write(s.Substring(s.LastIndexOf('\\') + 1));
Result: OrderConfirmation_SynergyWorldInc
IF YOU HAVE MULTIPLE RECORDS...
You can use a regex to extract multiple matches from a large text containing [...] substring:
[^\\\[\]]+(?=\])
See demo
For [HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc][SOMEENTRY] string, you will then get 2 results:
The regex matches
[^\\\[\]]+ - 1 or more characters other than ], [ and \
(?=\]) - before the end ] character.
C#:
var results = Regex.Matches(s, #"[^\\\[\]]+(?=\])").OfType<Match>().Select(p => p.Value).ToList();
var s = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
Console.WriteLine (s.Trim(']').Split('\\').Last());
prints
OrderConfirmation_SynergyWorldInc
var key = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
key = key.Replace("[", string.Empty);
key = key.Replace("]", string.Empty);
var splitkeys =key.Split('\\');
if (splitkeys.Any())
{
string result = splitkeys.Last();
}
Try:
string orderConfirmation = yourString.Split(new []{'\\\'}).Last();
You may also want to remove the last character if the brackets are included in the string.
string pattern = ".*\\(\w*)";
string value = "[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]"
Regex r = new Regex(pattern);
Match m = r.Match(value);
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("]", "");