Regex cut number in a string c# - c#

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;

Related

Get INT value between 2 matching chars

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);

.NET RegEx.Replace substring with special chars [duplicate]

I want to insert a dollar sign at a specific position between two named capturing groups. The problem is that this means two immediately following dollar-signs in the replacement-string which results in problems.
How am I able to do that directly with the Replace-method? I only found a workaround by adding some temporary garbage that I instantly remove again.
See code for the problem:
// We want to add a dollar sign before a number and use named groups for capturing;
// varying parts of the strings are in brackets []
// [somebody] has [some-dollar-amount] in his [something]
string joeHas = "Joe has 500 in his wallet.";
string jackHas = "Jack has 500 in his pocket.";
string jimHas = "Jim has 740 in his bag.";
string jasonHas = "Jason has 900 in his car.";
Regex dollarInsertion = new Regex(#"(?<start>^.*? has )(?<end>\d+ in his .*?$)", RegexOptions.Multiline);
Console.WriteLine(joeHas);
Console.WriteLine(jackHas);
Console.WriteLine(jimHas);
Console.WriteLine(jasonHas);
Console.WriteLine("--------------------------");
joeHas = dollarInsertion.Replace(joeHas, #"${start}$${end}");
jackHas = dollarInsertion.Replace(jackHas, #"${start}$-${end}");
jimHas = dollarInsertion.Replace(jimHas, #"${start}\$${end}");
jasonHas = dollarInsertion.Replace(jasonHas, #"${start}$kkkkkk----kkkk${end}").Replace("kkkkkk----kkkk", "");
Console.WriteLine(joeHas);
Console.WriteLine(jackHas);
Console.WriteLine(jimHas);
Console.WriteLine(jasonHas);
Output:
Joe has 500 in his wallet.
Jack has 500 in his pocket.
Jim has 740 in his bag.
Jason has 900 in his car.
--------------------------
Joe has ${end}
Jack has $-500 in his pocket.
Jim has \${end}
Jason has $900 in his car.
Use this replacement pattern: "${start}$$${end}"
The double $$ escapes the $ so that it is treated as a literal character. The third $ is really part of the named group ${end}. You can read about this on the MSDN Substitutions page.
I would stick with the above approach. Alternately you can use the Replace overload that accepts a MatchEvaluator and concatenate what you need, similar to the following:
jackHas = dollarInsertion.Replace(jackHas,
m => m.Groups["start"].Value + "$" + m.Groups["end"].Value);
Why are you using regex for this in the first place?
string name = "Joe";
int amount = 500;
string place = "car";
string output = string.Format("{0} has ${1} in his {2}",name,amount,place);

start from end of string till special character 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);

Substring or split word in clamp

I need an solution for my problem. I have a clause like:
Hello guys I am cool (test)
An now I need an effective method to split just only the part in the parentheses and the result should be:
test
My try is to split the String in words like. But I don't think it is the best way.
string[] words = s.Split(' ');
I do not think that split is the solution to your problem
Regex is very good for extracting data.
using System.Text.RegularExpression;
...
string result = Regex.Match(s, #"\((.*?)\)").Groups[1].Value;
This should do the trick.
Assuming:
var input = "Hello guys I am cool (test)";
..Non-Regex version:
var nonRegex = input.Substring(input.IndexOf('(') + 1, input.LastIndexOf(')') - (input.IndexOf('(') + 1));
..Regex version:
var regex = Regex.Match(input, #"\((\w+)\)").Groups[1].Value;
You can use regex for this:
string parenthesized = Regex.Match(s, #"(?<=\()[^)]+(?=\))").Value;
Here's an explanation of the various parts of the regex pattern:
(?<=\(): Lookbehind for the ( (excluded from the match)
[^)]+: Sequence of characters consisting of anything except )
(?=\)): Lookahead for the ) (excluded from the match)
The most efficient way is using string methods but you don't need Split but Substring and IndexOf. Note that this currently just finds a single word in parentheses:
string text = "Hello guys I am cool (test)";
string result = "--no parentheses--";
int index = text.IndexOf('(');
if(index++ >= 0) // ++ used to look behind ( which is a single character
{
int endIndex = text.IndexOf(')', index);
if(endIndex >= 0)
{
result = text.Substring(index, endIndex - index);
}
}
string s = "Hello guys I am cool (test)";
var result = s.Substring(s.IndexOf("test"), 4);

How to trim characters from certain patterned words in string?

Given the following string:
string s = "I need drop the 1 from the end of AAAAAAAA1 and BBBBBBBB1"
How can I trim the "1" from any 8 character string that ends in a 1? I got so far as to find a working Regex pattern that finds these strings, and I'm guessing I could use a TrimEnd to remove the "1", but how I do I modify the string itself?
Regex regex = new Regex("\\w{8}1");
foreach (Match match in regex.Matches(s))
{
MessageBox.Show(match.Value.TrimEnd('1'));
}
The result I'm looking for would be "I need drop the 1 from the end of AAAAAAAA and BBBBBBBB"
Regex.Replace is the tool for the job:
var regex = new Regex("\\b(\\w{8})1\\b");
regex.replace(s, "$1");
I slightly modified the regular expression to match the description of what you are trying to do more closely.
Here a non-regex approach:
s = string.Join(" ", s.Split().Select(w => w.Length == 9 && w.EndsWith("1") ? w.Substring(0, 8) : w));
In VB with LINQ:
Dim l = 8
Dim s = "I need drop the 1 from the end of AAAAAAAA1 and BBBBBBBB1"
Dim d = s.Split(" ").Aggregate(Function(p1, p2) p1 & " " & If(p2.Length = l + 1 And p2.EndsWith("1"), p2.Substring(0, p2.Length - 1), p2))
Try this:
s = s.Replace(match.Value, match.Value.TrimEnd('1'));
And the s string will have the value you want.

Categories