Extract number from end of string [duplicate] - c#

This question already has answers here:
Find and extract a number from a string
(32 answers)
Closed 8 years ago.
I have some strings like "pan1", "pan2", and "pan20" etc. I need to extract number. I use it:
char ch = s[(s.Length) - 1];
int n = Convert.ToInt32(Char.GetNumericValue(ch));
But in case of, for example, "pan20" the result is not correct 0.

Index Approach
if you know where is the starting index of the number then simply you can do this :
string str = "pan20";
int number = Convert.ToInt32(str.Substring(3));
Note that "3" is the starting index of the number.
Fixed Prefix Approach
try to remove "pan" from the string; like this
string str = "pan20";
int number = Convert.ToInt32(str.Replace("pan", ""));
Regular Expression Approach
use regular expression only when string contains undetermined text inside
string str = "pan20";
int number = Convert.ToInt32(System.Text.RegularExpressions.Regex.Match(str, #"\d+").Value;

You can use for example regular expressions, for example [0-9]+$ to get the numbers in the end. See the Regex class in MSDN.

Related

How to find the immediate integer value written before a string? [duplicate]

This question already has answers here:
How to get the digits before some particular word using regex in c#?
(8 answers)
Closed 2 years ago.
How to find the immediate integer value written before a string in c#? For example
50+ boxes were ordered, however only 2 are delivered.
I need to know the number of boxes (integer value) written just before "delivered". The output should be 2. I have written a code in c# using Regex:
string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, #"\d+").Value;
//The output I get is 50 instead of 2.
To get the last number that is followed by the word "delivered", you may use the following pattern:
\b\d+\b(?=[^\d]*\bdelivered\b)
Regex demo.
Here's a full example:
string line = "50+ boxes were ordered, however only 2 are delivered.";
var match = Regex.Match(line, #"\b\d+\b(?=[^\d]*\bdelivered\b)");
if (match.Success)
{
string boxesDelivered = match.Value;
// TODO: convert the value to a numeric type or use it as is.
}
Try it online.
written just before delivered
I'm going to take that verbatim as your user requirement - find the last number in the string that appears before "delivered".
You can use (\d+)[^\d]*(?:delivered), which says "match any sequence of numbers that does not occur before another sequence of numbers and does occur before delivered".
string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, #"(\d+)[^\d]*(?:delivered)").Groups[1].Value;
// boxesDelivered = 2

c# Leave last 3 letters in a string [duplicate]

This question already has answers here:
Extract only right most n letters from a string
(22 answers)
Closed 2 years ago.
How to remove letters from the string and leave just 3 last chars
Input:
foobar
Output:
bar
I tried:
string.Concat("foobar".Reverse().Skip(3).Reverse());
But that removes last 3 lines not keeps them
Well, you can try Substring: if source is long enough we get Substring otherwise leave source intact:
string source = ...
string result = source.Length > 3
? source.Substring(source.Length - 3)
: source;
Or even
string result = source.Substring(Math.Max(0, source.Length - 3));
Since C# 8, you can also use range syntax:
string result = source.Length > 3 ? source[^3..] : source;
or:
string result = source[^Math.Min(3, source.Length)..];
[^3..] is a range which means "start 3 elements from the end, and keep going until the end".
There is a one line solution as well. Just check whether source string has enough length to get last 3 characters using Substring or leave string as is. Math.Max function will return a correct index
var str = "foobar";
var result = str.Substring(Math.Max(0, str.Length - 3));

Get the rest of the string after occurrence of particular letters [duplicate]

This question already has answers here:
Regular Expression Groups in C#
(5 answers)
Closed 4 years ago.
string ABC = "This is test AZ12346";
Need value that occurs after AZ. AZ will always be present in the string and it will always be the last word. But number of characters after AZ will vary.
Output should be : AZ123456
Simply :
ABC.Substring(ABC.LastIndexOf("AZ"));
You can try LastIndexOf and Substring:
string ABC = "This is test AZ12346";
string delimiter = "AZ";
// "AZ123456"
string result = ABC.Substring(ABC.LastIndexOf(delimiter));
In case delimiter can be abscent
int p = ABC.LastIndexOf(delimiter);
string result = p >= 0
? ABC.Substring(p)
: result; // No delimiter found
If you are looking for whole word which starts from AZ (e.g. "AZ123", but not "123DCAZDE456" - AZ in the middle of the word) you can try regular expressions
var result = Regex
.Match(ABC, #"\bAZ[A-Za-z0-9]+\b", RegexOptions.RightToLeft)
.Value;

how to split a string based on integers occurrence? [duplicate]

This question already has answers here:
How to get the last five characters of a string using Substring() in C#?
(12 answers)
Closed 4 years ago.
If a string that contains integers and I want to split it based on integers occurrence. how to do that?
string test= "a b cdf 7654321;
then I want to store the integer and all words before it, like this
string stringBefore="";
// the integer will be last item
string integer="";
Note:
in my case the integer always will be 7 digits
You can use Regex.Split with a capture group to return the delimiter:
var ans = Regex.Split(test, #"("\d{7})");
If the number is at the end of the string, this will return an extra empty string. If you know it is always at the end of the string, you can split on its occurrence:
var ans = Regex.Split(test, #"(?=\d{7})");
According to your comments the integer is always 7 digits and it is always the last item of the string.
In that case, just use Substring()
string test = "a b cdf 7654321";
string stringBefore = test.Substring(0, test.Length - 7);
string integer = test.Substring(test.Length - 7);
Substring just makes a string based on a portion of your original string.
EDIT
I was a little surprised to find there wasn't a built in way to easily split a string in to two strings based on an index (maybe I missed it). I came up with a LINQ extension method that achieves what I was trying to do, maybe you will find it useful:
public static string[] SplitString(this string input, int index)
{
if(index < 0 || input.Length < index)
throw new IndexOutOfRangeException();
return new string[]
{
String.Concat(input.Take(input.Length - index)),
String.Concat(input.Skip(input.Length - index))
};
}
I think I would rather use a ValueTuple if using C# 7, but string array would work too.
Fiddle for everything here

Regex Limit the count of characters in a string [duplicate]

This question already has answers here:
How would you count occurrences of a string (actually a char) within a string?
(34 answers)
Closed 9 years ago.
Here is my string
string countCommas = 12,34,56
I am looking for REGEX for algorithm below
BOOL isCountExaclty2 = if(number of commas in string == 2){return TRUE;}else return FALSE
I want the right hand expression as one single REGEX expression which returns either TRUE or FALSE but not the count
(I know to use Regex.COUNT..but it ends up in 2 statements)
If you're looking for a pattern that will only match if there's exactly two commas in the string, this should work:
bool isCountExactly2 = Regex.IsMatch("12,34,56", "^([^,]*,){2}[^,]*$");
But regular expressions really aren't the right tool for this job.
Try this :
string countCommas = "12,34,56"
bool isCountExaclty2 = Regex.Split(countCommas, ",").Length == 2;

Categories

Resources