I want to retrieve characters separated by a specific delimiter.
Example :
Here, I want to access the string between the " " delimiters. But I want the 2nd set of characters between "".
abc"def"ghi"jklm // Output : ghi
"hello" yes "world" // output : world
How can I get that?
I know we can use split. But sometimes the string might not start with " character.
Can anyone please help me with this?
You can just find the first quote, and use your approach from there:
var firstQuote = str.IndexOf('"');
var startsWithQuote = str.Substring(firstQuote);
string valueStr = "abc\"def\"ghi\"jklm";
var result = valueStr.Split('"')[2];
Console.WriteLine(result);
https://dotnetfiddle.net/T3fMof
Obviously check for the array elements before accessing them
You can use regular expressions to match them:
var test = "abc\"def\"ghi\"jklm";
var test2 = "\"hello\" yes \"world\"";
var match1 = Regex.Matches(test, ".+\"(.+)\"");
var match2 = Regex.Matches(test2, ".+\"(.+)\"");
Console.WriteLine("Match1: " + match1[0].Groups[1].Captures[0]);
Console.WriteLine("Match2: " + match2[0].Groups[1].Captures[0]);
// Match1: ghi
// Match2: world
Related
I have the following string:
bank_38024032jr3020893 = bank_38024032jr3020893 + (call randomFunc) + 15;" \n
I want to to find and replace the bank_38024032jr3020893 with let say bank_hello how would I go at doing that? bank_38024032jr3020893 could change and I still want to be able to change it to whatever (bank_hello in the example).
I've found some good examples with regex but cant get that to work.
So what I want to is when it finds bank_xxxOldxxxit should replace that part with bank_whateverIwant
This is what I've tried:
string input2 = "bank_4556457 = bank_4556457 + (call randomFunc) + 15; \n";
string pattern2 = #"bank_";
string replace2 = "bank_55444";
string result2 = Regex.Replace(input2, pattern2, replace2);
Console.WriteLine(result2);
I understand that I cant grab the things after the "_" with that but not sure how to edit the code to fix my issue
Test this on your console:
string input = ReadLine();
WriteLine(Regex.Replace(input,"test_(\\d|[a-zA-Z])+","NewTest123"));
ReadKey();
\d matches any number, and the '+' sign means that is matches as many occurrences possible.
You should take a look at: Regular Expression in c#
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);
For Example, I have a string like :
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
I want to delete the charaters ,phani from str.
Now, I am using str = str.Replace(",phani", string.Empty);
then my output is : str="santhosh,ravi123,praveen,sathish,prakash";
But I want a output like : str="santhosh,ravi,phani123,praveen,sathish,prakash";
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
var words = str.Split(',');
str = String.Join(",", words.Where(word => word != "phani"));
the better choice is to use a Split and Join method.
Easy in Linq :
String str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
String token = "phani";
String result = String.Join(",", str.Split(',').Where(s => s != token));
(edit : I take time for testing and i'm not first ^^)
String.join(",", str.split(',').ToList().remove("phani"));
Removes any given name from the list.
How about
str = str.Replace(",phani,", ",");
This, however, does not work if "phani" is the last item in the string. To get around this, you could do this:
string source = "...";
source += ","; // Explicitly add a comma to the end
source = source.Replace(",phani,", ",").TrimEnd(',');
This adds a comma, replaces "phani" and removes the trailing comma.
A third solution would be this:
str = String.Join(",", str.Split(',').ToList().Remove("phani").ToArray());
Try to use with comma instead of;
string str = "santhosh,ravi,phani,phani123,praveen,sathish,prakash";
str = str.Replace(",phani,", ",");
Console.WriteLine(str);
Output will be;
santhosh,ravi,phani123,praveen,sathish,prakash
Here is a DEMO.
As Davin mentioned in comment, this won't work if phani is last item in the string. Silvermind's answer looks like the right answer.
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
string pattern = #"\b,phani,\b";
string replace = ",";
Console.WriteLine(Regex.Replace(str, pattern, replace));
Output:
santhosh,ravi,phani123,praveen,sathish,prakash
You may use the regular expression, but you have to take care of cases when your string starts or ends with the substring:
var pattern = #",?\bphani\b,?";
var regex = new Regex(pattern);
var result = regex.Replace(input, ",").Trim(',');
Shorter notation could look like this:
var result = Regex.Replace(input, #",?\bphani\b,?", ",").Trim(',');
Explanation of the regular expression: ,?\bphani\b,? matches the word phani, but only if preceded and followed by word-delimiter characters (because of the word boundary metacharacter \b), and it can be (but doesn't have to be) preceded and followed by the comma thanks to ,? which means none or more comma(s).
At the end we need to remove possible commas from the beginning and end of the string, that's why there's Trim(',') on the result.
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));
please help me this problem.
I want to split "-action=1" to "action" and "1".
string pattern = #"^-(\S+)=(\S+)$";
Regex regex = new Regex(pattern);
string myText = "-action=1";
string[] result = regex.Split(myText);
I don't know why result have length=4.
result[0] = ""
result[1] = "action"
result[2] = "1"
result[3] = ""
Please help me.
P/S: I am using .NET 2.0.
Thanks.
Hello, I tested with string: #"-destination=C:\Program Files\Release" but it have inaccurate result, I don't understand why result's length = 1. I think because it has a white space in string.
I want to split it to "destination" & "C:\Program Files\Release"
More info: This is my requirement:
-string1=string2 -> split it to: string1 & string2.
In string1 & string2 don't contain characters: '-', '=', but they can contain white space.
Please help me. Thanks.
Don't use split, just use Match, and then get the results from the Groups collection by index (index 1 and 2).
Match match = regex.Match(myText);
if (!match.Success) {
// the regex didn't match - you can do error handling here
}
string action = match.Groups[1].Value;
string number = match.Groups[2].Value;
Try this (updated to add Regex.Split):
string victim = "-action=1";
string[] stringSplit = victim.Split("-=".ToCharArray());
string[] regexSplit = Regex.Split(victim, "[-=]");
EDIT: Using your example:
string input = #"-destination=C:\Program Files\Release -action=value";
foreach(Match match in Regex.Matches(input, #"-(?<name>\w+)=(?<value>[^=-]*)"))
{
Console.WriteLine("{0}", match.Value);
Console.WriteLine("\tname = {0}", match.Groups["name" ].Value);
Console.WriteLine("\tvalue = {0}", match.Groups["value"].Value);
}
Console.ReadLine();
Of course, this code have issues if your path contains - character
In .NET Regex, you can name your groups.
string pattern = #"^-(?<MyKey>\S+)=(?<MyValue>\S+)$";
Regex regex = new Regex(pattern);
string myText = "-action=1";
Then do a "Match" and get the values by your group names.
Match theMatch = regex.Match(myText);
if (theMatch.Success)
{
Console.Write(theMatch.Groups["MyKey"].Value); // This is "action"
Console.Write(theMatch.Groups["MyValue"].Value); // This is "1"
}
What's wrong with using string.split()?
string test = "-action=1";
string[] splitUp = test.Split("-=".ToCharArray());
I admit, though that this still gives you possibly more parameters than you'd like to see in the split up array...
[0] = ""
[1] = "action"
[2] = "1"
In his talk Regular Expression Mastery, Mark Dominus attributes the following helpful rule to Learning Perl author (and fellow StackOverflow user) Randal Schwartz:
Use capturing or m//g [or regex.Match(...)] when you know what you want to keep.
Use split when you know what you want to throw away.