Regex after character - c#

I am trying to use a regex to get the value after a character. In this case, the string is m325 and I need to get whatever is after the m.
Can anybody tell me what is wrong with my code?
Regex rgMeter = new Regex("m(.+$");
intMeterID = Convert.ToInt32(rgMeter.Match(strID));
Update:
Thanks for all your answers...for some reason the regex "m(.+)$" is returning the m as well as the string I require. I have tried the Groups example and it returns the data that I want. Why do I need to use Groups to do this?

Apart from the missing ), you oversimplified it a bit. You need to do
Regex rgMeter = new Regex("m(.+)$");
intMeterID = Convert.ToInt32(rgMeter.Match(strID).Groups[1].Value);
(Possibly, you might want to add a check if the Match() matched or not.)

You are missing a closing ). Plus, if you are extracting a number you should limit yourself to digits only, Will avoid trying to parse a faulty string into integer in the next statement.
m(\d*)

"m(.+)$" - there wasn't closed (

Also, you can test it on: http://gskinner.com/RegExr/
What values can appear behind the "m" character?
If it's only an integer, the I should use the solution Shekhar_Pro provided..
If any character, go with the rest :)

The regex you require is /^m(.*)$/
Actually you should use \d or [0-9] if you want match digits.
/^m([0-9]*)$/
and
/^m([0-9]{3})$/
if there are always 3 digits

Looks like you missed the closing )

A simple "m\d*" should do this.. please show us whole string to see the case.

Related

How do I regex split with variable values?

I have the following string:
21>Please be specific. What do you mean by that?21>Hello are you there623>Simon?
I want to split it into:
21>Please be specific. What do you mean by that?
21>Hello are you there
623>Simon?
Basically the splitter is the numeric value (21 and 623 in this case) followed by the >.
My implementation is that I find the > char, then walk back until I find a non-numeric value.
So basically using sub-string and the like. But it's ugly and I am certain there is a better Regex implementation, but I don't know enough about it.
So can Regex be used here?
You can achieve that with look ahead and look behind, so that your match is the zero length area between what you want to split.
string s = "21>Please be specific. What do you mean by that?21>Hello are you there623>Simon?";
Regex reg = new Regex(#"(?<=\D)(?=\d+>)");
var r = reg.Split(s);
foreach(var i in r)
Console.WriteLine(i);
Will output
21>Please be specific. What do you mean by that?
21>Hello are you there
623>Simon?
Try with following regex. It matches the zero width between something and number>
Regex: (?<=\D)(?=\d+>) replaced with \n for demo.
Explanation:
(?<=\D) looks behind to see if it's not a number.
(?=\d+>) looks ahead to see if it's a number>.
And matched the zer0-width between them.
Regex101 Demo
Try: [0-9]+>
Explanation:
[0-9]+ At least 1 digit
> followed by >
It might make sense to replace the matches with \n$0, which will move them to individual lines.

Regex - find every occurrence of integer surrounded by space and coma

I have the following string:
"121 fd412 4151 3213, 421, 423 41241 fdsfsd"
And I need to get 3213 and 421 - because they both have space in front of them, and a coma behind.
The result will be set inside the string array...How can I do that?
"\\d+" catches every integer.
"\s\\d+(,)" throws some memory errors.
EDIT.
space to the left (<-) of the number, coma to the right (->)
EDIT 2.
string mainString = "Tests run: 5816, 8346, 28364 iansufbiausbfbabsbo3 4";
MatchCollection c = Regex.Matches(a, #"\d+(?=\,)");
var myList = new List<String>();
foreach(Match match in c)
{
myList.Add(match.Value);
}
Console.Write(myList[1]);
Console.ReadKey();
Your regex syntax is incorrect for wanting to match both digits, if you want them as separate results, you could do:
#"\s(\d+),\s(\d+)\s"
Live Demo
Edit
#"\s(\d+),"
Live Demo
\s\\d+(,):
\s is not properly escaped, should be \\s, same as for \\d
\\d matches single digit, you need \\d+ - one or more consecutive digits
(,) captures comma, do you really need this? seems like you need to capture a number, so \\s(\\d+),
you said "because they both have space behind them, and a coma in front", so probably ,\\s(\\d+)
How about this expression :
" \d+," // expression without the quotes
it should find what you need.
How to work with regular expression can you check on the MSDN
Hope it helps
Another solution
\s(\d+), // or maybe you'll need a double slash \\
Output:
3213
421
Demo
I think you mean you're looking for something like ,<space><digit> not ,<digit><space>
If so, try this:
, (\d+) //you might need to add another backslash as the others have noted
Well, based on your new edit
\s(\d+),
Test it here
It's all you need, only the numbers
\d+(?=\,)

What regex to use to get a number from a string that may or may not have a decimal part?

Example strings
asda25asd.56asda
a$asdas23asdas
as$dasd.56asdasd
The current best one I have is
\$?.*?(?<AmountInt>\d+).*(?<AmountDecimal>\.\d+)?.*
but it doesn't capture the .56 in the first string and doesn't work for other strings. Any ideas ?
Why all the noise? (?<AmountInt>\d+)(?<AmountDecimal>\.\d+)? should be enough.
Now, AmoutInt is \d+ so you must have an integer figure before the dot. Otherwise use \d*
EDIT- OK, I understand better your requirement. But the .* between the groups is greedy. Try .*?instead.

Check Formatting of a String

This has probably been answered somewhere before but since there are millions of unrelated posts about string formatting.
Take the following string:
24:Something(true;false;true)[0,1,0]
I want to be able to do two things in this case. I need to check whether or not all the following conditions are true:
There is only one : Achieved using Split() which I needed to use anyway to separate the two parts.
The integer before the : is a 1-3 digit int Simple int.parse logic
The () exists, and that the "Something", in this case any string less than 10 characters, is there
The [] exists and has at least 1 integer in it. Also, make sure the elements in the [] are integers separated by ,
How can I best do this?
EDIT: I have crossed out what I've achieved so far.
A regular expression is the quickest way. Depending on the complexity it may also be the most computationally expensive.
This seems to do what you need (I'm not that good so there might be better ways to do this):
^\d{1,3}:\w{1,9}\((true|false)(;true|;false)*\)\[\d(,[\d])*\]$
Explanation
\d{1,3}
1 to 3 digits
:
followed by a colon
\w{1,9}
followed by a 1-9 character alpha-numeric string,
\((true|false)(;true|;false)*\)
followed by parenthesis containing "true" or "false" followed by any number of ";true" or ";false",
\[\d(,[\d])*\]
followed by another set of parenthesis containing a digit, followed by any number of comma+digit.
The ^ and $ at the beginning and end of the string indicate the start and end of the string which is important since we're trying to verify the entire string matches the format.
Code Sample
var input = "24:Something(true;false;true)[0,1,0]";
var regex = new System.Text.RegularExpressions.Regex(#"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
bool isFormattedCorrectly = regex.IsMatch(input);
Credit # Ian Nelson
This is one of those cases where your only sensible option is to use a Regular Expression.
My hasty attempt is something like:
var input = "24:Something(true;false;true)[0,1,0]";
var regex = new System.Text.RegularExpressions.Regex(#"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
System.Diagnostics.Debug.Assert(regex.IsMatch(input));
This online RegEx tester should help refine the expression.
I think, the best way is to use regular expressions like this:
string s = "24:Something(true;false;true)[0,1,0]";
Regex pattern = new Regex(#"^\d{1,3}:[a-zA-z]{1,10}\((true|false)(;true|;false)*\)\[\d(,\d)*\]$");
if (pattern.IsMatch(s))
{
// s is valid
}
If you want anything inside (), you can use following regex:
#"^\d{1,3}:[a-zA-z]{1,10}\([^:\(]*\)\[\d(,\d)*\]$"

Pulling data out of quotes?

I'm looking for a regex that can pull out quoted sections in a string, both single and double quotes.
IE:
"This is 'an example', \"of an input string\""
Matches:
an example
of an input string
I wrote up this:
[\"|'][A-Za-z0-9\\W]+[\"|']
It works but does anyone see any flaws with it?
EDIT: The main issue I see is that it can't handle nested quotes.
How does it handle single quotes inside of double quotes (or vice versa)?
"This is 'an example', \"of 'quotes within quotes'\""
should match
an example
of 'quotes within quotes'
Use a backreference if you need to support this.
(\"|')[A-Za-z0-9\\W]+?\1
EDIT: Fixed to use a reluctant quantifier.
Like that?
"([\"'])(.*?)\1"
Your desired match would be in sub group 2, and the kind of quote in group one.
The flaw in your regex is 1) the greedy "+" and 2) [A-Za-z0-9] is not really matching an awful lot. Many characters are not in that range.
It works but doesn't match other characters in quotes (e.g., non-alphanumeric, like binary or foreign language chars). How about this:
[\"']([^\"']*)[\"']
My C# regex is a little rusty so go easy on me if that's not exactly right :)
#"(\"|')(.*?)\1"
You might already have one of these, but, in case not, here's a free, open source tool I use all the time to test my regular expressions. I typically have the general idea of what the expression should look like, but need to fiddle around with some of the particulars.
http://renschler.net/RegexBuilder/

Categories

Resources