I have a string of numbers separated by some non-numeric character like this: "16-15316-273"
Is it possible to build regex expression the way it returns me Nth matching group? I heard that ${n} might help, but it does not work for me at least in this expression:
// Example: I want to get 15316
var r = new Regex(#"(\d+)${1}");
var m = r.Match("16-15316-273");
(\d+)${0} returns 16, but (\d+)${1} gives me 273 instead of expected 15316
So N which is order of pattern needed to be extracted and input string itself ("16-15316-273" is just an example) are dynamic values which might change during app execution. The task is to build regex expression the way where the only thing changed inside it is N, and to be applicable to any such string.
Please do not offer solutions with any additional c# code like m.Groups[n] or Split, I'm intentionally asking for building proper Regex pattern for that. In short, I can not modify the code for every new N value, all I can modify is regex expression which is built dynamically, N will be passed as a parameter to the method. All the rest is static, no way to change it.
Maybe this expression will help you?
(?<=(\d+[^\d]+){1})\d+
You will need to modify {1} according to your N.
I.e.
(?<=(\d+[^\d]+){0})\d+ => 16
(?<=(\d+[^\d]+){1})\d+ => 15316
(?<=(\d+[^\d]+){2})\d+ => 273
Your regular expression
(\d+)${1}
says to match this:
(\d+): match 1 or more decimal digits, followed by
${1}: match the atomic zero-width assertion "end of input string" exactly once.
One should note that the {1} quantifier is redundant since there's normally only one end-of-input-string (unless you've turned on the multiline option).
That's why you're matching `273': it's the longest sequence of digits anchored at end-of-string.
You need to use a zero-width positive look-behind assertion. To capture the Nth field in your string, you need to capture that string of digits that is preceded by N-1 fields. Given this source string:
string input = "1-22-333-4444-55555-666666-7777777-88888888-999999999" ;
The regular expression to match the 3rd field, where the first field is 1 rather than 0 looks like this:
(?<=^(\d+(-|$)){2})\d+
It says to
match the longest sequence of digits that is preceded by
start of text, followed by
a group, consisting of
1 or more decimal digits, followed by
either a - or end-of-text
with that group repeated exactly 2 times
Here's a sample program:
string src = "1-22-333-4444-55555-666666-7777777-88888888-999999999" ;
for ( int n = 1 ; n <= 10 ; ++n )
{
int n1 = n-1 ;
string x = n1.ToString(CultureInfo.InvariantCulture) ;
string regex = #"(?<=^(\d+(-|$)){"+ x + #"})\d+" ;
Console.Write( "regex: {0} ",regex);
Regex rx = new Regex( regex ) ;
Match m = rx.Match( src ) ;
Console.WriteLine( "N={0,-2}, N-1={1,-2}, {2}" ,
n ,
n1 ,
m.Success ? "success: " + m.Value : "failure"
) ;
}
It produces this output:
regex: (?<=^(\d+(-|$)){0})\d+ N= 1, N-1=0 , success: 1
regex: (?<=^(\d+(-|$)){1})\d+ N= 2, N-1=1 , success: 22
regex: (?<=^(\d+(-|$)){2})\d+ N= 3, N-1=2 , success: 333
regex: (?<=^(\d+(-|$)){3})\d+ N= 4, N-1=3 , success: 4444
regex: (?<=^(\d+(-|$)){4})\d+ N= 5, N-1=4 , success: 55555
regex: (?<=^(\d+(-|$)){5})\d+ N= 6, N-1=5 , success: 666666
regex: (?<=^(\d+(-|$)){6})\d+ N= 7, N-1=6 , success: 7777777
regex: (?<=^(\d+(-|$)){7})\d+ N= 8, N-1=7 , success: 88888888
regex: (?<=^(\d+(-|$)){8})\d+ N= 9, N-1=8 , success: 999999999
regex: (?<=^(\d+(-|$)){9})\d+ N=10, N-1=9 , failure
Try this:
string text = "16-15316-273";
Regex r = new Regex(#"\d+");
var m = r.Match(text, text.IndexOf('-'));
The output is 15316 ;)
Related
Here i have following strings ,
"#,##0.00"
"\"$\"#,##0.0000"
I need to split using regular expressions.
My Expected output is
"#,##0.00" => 2 (decimal)
"\"$\"#,##0.0000" => $4(4 decimal with $)
How to convert can u please suggest any way.
Thanks
You may use the following regex:
^(?:"([^"]+)")?.*?(0+)$
The pattern matches:
^ - start of string
(?:"([^"]+)")? - 1 or 0 sequences of:
" - a double quote
([^"]+) - Group 1 capturing 1 or more chars other than "
"
.*? - any characters other than newline, 0 or more repetitions
(0+) - Group 2 capturing 1 or more zeros
$ - end of string
And here is a C# demo:
var pat = #"^(?:""([^""]+)"")?.*?(0+)$";
var match = Regex.Match("#.##0.00", pat);
if (match.Success) {
Console.WriteLine(match.Groups[1].Value + match.Groups[2].Length.ToString());
} // => 2
// With "\"$\"#,##0.0000" input: $4
See the IDEONE demo
I have a long string and I have a var inside it
var abc = '123456'
Now I wish to get the 123456 from it.
I have tried a regex but its not working properly
Regex regex = new Regex("(?<abc>+)=(?<var>+)");
Match m = regex.Match(body);
if (m.Success)
{
string key = m.Groups["var"].Value;
}
How can I get the number from the var abc?
Thanks for your help and time
var body = #" fsd fsda f var abc = '123456' fsda fasd f";
Regex regex = new Regex(#"var (?<name>\w*) = '(?<number>\d*)'");
Match m = regex.Match(body);
Console.WriteLine("name: " + m.Groups["name"]);
Console.WriteLine("number: " + m.Groups["number"]);
prints:
name: abc
number: 123456
Your regex is not correct:
(?<abc>+)=(?<var>+)
The + are quantifiers meaning that the previous characters are repeated at least once (and there are no characters since (?< ... > ... ) is named capture group and is not considered as a character per se.
You perhaps meant:
(?<abc>.+)=(?<var>.+)
And a better regex might be:
(?<abc>[^=]+)=\s*'(?<var>[^']+)'
[^=]+ will match any character except an equal sign.
\s* means any number of space characters (will also match tabs, newlines and form feeds though)
[^']+ will match any character except a single quote.
To specifically match the variable abc, you then put it like this:
(?<abc>abc)\s*=\s*'(?<var>[^']+)'
(I added some more allowances for spaces)
From the example you provided the number can be gotten such as
Console.WriteLine (
Regex.Match("var abc = '123456'", #"(?<var>\d+)").Groups["var"].Value); // 123456
\d+ means 1 or more numbers (digits).
But I surmise your data doesn't look like your example.
Try this:
var body = #"my word 1, my word 2, my word var abc = '123456' 3, my word x";
Regex regex = new Regex(#"(?<=var \w+ = ')\d+");
Match m = regex.Match(body);
Suppose I have a string
Likes (20)
I want to fetch the sub-string enclosed in round brackets (in above case its 20) from this string. This sub-string can change dynamically at runtime. It might be any other number from 0 to infinity. To achieve this my idea is to use a for loop that traverses the whole string and then when a ( is present, it starts adding the characters to another character array and when ) is encountered, it stops adding the characters and returns the array. But I think this might have poor performance. I know very little about regular expressions, so is there a regular expression solution available or any function that can do that in an efficient way?
If you don't fancy using regex you could use Split:
string foo = "Likes (20)";
string[] arr = foo.Split(new char[]{ '(', ')' }, StringSplitOptions.None);
string count = arr[1];
Count = 20
This will work fine regardless of the number in the brackets ()
e.g:
Likes (242535345)
Will give:
242535345
Works also with pure string methods:
string result = "Likes (20)";
int index = result.IndexOf('(');
if (index >= 0)
{
result = result.Substring(index + 1); // take part behind (
index = result.IndexOf(')');
if (index >= 0)
result = result.Remove(index); // remove part from )
}
Demo
For a strict matching, you can do:
Regex reg = new Regex(#"^Likes\((\d+)\)$");
Match m = reg.Match(yourstring);
this way you'll have all you need in m.Groups[1].Value.
As suggested from I4V, assuming you have only that sequence of digits in the whole string, as in your example, you can use the simpler version:
var res = Regex.Match(str,#"\d+")
and in this canse, you can get the value you are looking for with res.Value
EDIT
In case the value enclosed in brackets is not just numbers, you can just change the \d with something like [\w\d\s] if you want to allow in there alphabetic characters, digits and spaces.
Even with Linq:
var s = "Likes (20)";
var s1 = new string(s.SkipWhile(x => x != '(').Skip(1).TakeWhile(x => x != ')').ToArray());
const string likes = "Likes (20)";
int likesCount = int.Parse(likes.Substring(likes.IndexOf('(') + 1, (likes.Length - likes.IndexOf(')') + 1 )));
Matching when the part in paranthesis is supposed to be a number;
string inputstring="Likes (20)"
Regex reg=new Regex(#"\((\d+)\)")
string num= reg.Match(inputstring).Groups[1].Value
Explanation:
By definition regexp matches a substring, so unless you indicate otherwise the string you are looking for can occur at any place in your string.
\d stand for digits. It will match any single digit.
We want it to potentially be repeated several times, and we want at least one. The + sign is regexp for previous symbol or group repeated 1 or more times.
So \d+ will match one or more digits. It will match 20.
To insure that we get the number that is in paranteses we say that it should be between ( and ). These are special characters in regexp so we need to escape them.
(\d+) would match (20), and we are almost there.
Since we want the part inside the parantheses, and not including the parantheses we tell regexp that the digits part is a single group.
We do that by using parantheses in our regexp. ((\d+)) will still match (20), but now it will note that 20 is a subgroup of this match and we can fetch it by Match.Groups[].
For any string in parantheses things gets a little bit harder.
Regex reg=new Regex(#"\((.+)\)")
Would work for many strings. (the dot matches any character) But if the input is something like "This is an example(parantesis1)(parantesis2)", you would match (parantesis1)(parantesis2) with parantesis1)(parantesis2 as the captured subgroup. This is unlikely to be what you are after.
The solution can be to do the matching for "any character exept a closing paranthesis"
Regex reg=new Regex(#"\(([^\(]+)\)")
This will find (parantesis1) as the first match, with parantesis1 as .Groups[1].
It will still fail for nested paranthesis, but since regular expressions are not the correct tool for nested paranthesis I feel that this case is a bit out of scope.
If you know that the string always starts with "Likes " before the group then Saves solution is better.
I'm trying to separate the tokens on a string expression. The expression looks like this:
-1-2+-3
This is the regex I'm using:
[\d\.]+|[-][\d\.]+|\+|\-|\*|\/|\^|\(|\)
This brings me these matches:
-1
-2
+
-3
I was expecting:
-1
-
2
+
-3
Any ideas how can I distinct negative numbers from operators?
Maybe you could try this one; it makes use of a look-behind:
((?<=\d)[+*\/^()-]|\-?[\d.]+)
I tested it here.
Basically, makes sure that there is a number before the operator to decide what to match. So, if there is a digit before the operator, treat the operator alone, otherwise, combine the minus with the digit.
EDIT: Separated the brackets from the lot, just in case (demo):
((?<=\d)[+*\/^-]|[()]|\-?[\d.]+)
This pattern should do what you're looking for:
^(?:(?<num>-?[\d\.]+)(?:(?<op>[-+*/^])|$))+$
For example:
var input = "-1-2+-3";
var pattern = #"^(?:(?<num>-?[\d\.]+)(?:(?<op>[-+*/^])|$))+$";
var match = Regex.Match(input, pattern);
var results =
from Group g in match.Groups.Cast<Group>().Skip(1)
from Capture c in g.Captures
orderby c.Index
select c.Value;
Will produce:
-1
-
2
+
-3
I currently have a regex that pulls up a 16 digit number from a file e.g.:
Regex:
Regex.Match(l, #"\d{16}")
This would work well for a number as follows:
1234567891234567
Although how could I also include numbers in the regex such as:
1234 5678 9123 4567
and
1234-5678-9123-4567
If all groups are always 4 digit long:
\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}\b
to be sure the delimiter is the same between groups:
\b\d{4}(| |-)\d{4}\1\d{4}\1\d{4}\b
If it's always all together or groups of fours, then one way to do this with a single regex is something like:
Regex.Match(l, #"\d{16}|\d{4}[- ]\d{4}[- ]\d{4}[- ]\d{4}")
You could try something like:
^([0-9]{4}[\s-]?){3}([0-9]{4})$
That should do the trick.
Please note:
This also allows
1234-5678 9123 4567
It's not strict on only dashes or only spaces.
Another option is to just use the regex you currently have, and strip all offending characters out of the string before you run the regex:
var input = fileValue.Replace("-",string.Empty).Replace(" ",string.Empty);
Regex.Match(input, #"\d{16}");
Here is a pattern which will get all the numbers and strip out the dashes or spaces. Note it also checks to validate that there is only 16 numbers. The ignore option is so the pattern is commented, it doesn't affect the match processing.
string value = "1234-5678-9123-4567";
string pattern = #"
^ # Beginning of line
( # Place into capture groups for 1 match
(?<Number>\d{4}) # Place into named group capture
(?:[\s-]?) # Allow for a space or dash optional
){4} # Get 4 groups
(?!\d) # 17th number, do not match! abort
$ # End constraint to keep int in 16 digits
";
var result = Regex.Match(value, pattern, RegexOptions.IgnorePatternWhitespace)
.Groups["Number"].Captures
.OfType<Capture>()
.Aggregate (string.Empty, (seed, current) => seed + current);
Console.WriteLine ( result ); // 1234567891234567
// Shows False due to 17 numbers!
Console.WriteLine ( Regex.IsMatch("1234-5678-9123-45678", pattern, RegexOptions.IgnorePatternWhitespace));