Find number in string - c#

How to find number(int, float) in a string (fast method)?
For example: "Question 1" and "Question 2.1".
I need that in variable would be only number.
Thanks.

you can use this ([0-9]\.*)*[0-9] regex to get it. you can test any regex here
Edit
this sample code in C#
Regex regexpattern = new Regex(#"(([0-9]\.*)*[0-9])");
String test = #"Question 1 and Question 2.1.3";
foreach (Match match in regexpattern.Matches(test))
{
String language = match.Groups[1].Value;
}

You can use Reqular Expressions. To search numbers try this:
var r = System.Text.RegularExpressions.Regex.Match("Question 2.1", "\d+");

There's always the good ol' regular expressions! It wouldn't give you a float for "2.1" though, but I'm not sure that's a good idea since there's always the possibility of "2.1.4" or even "2a". Might be best to store a vector of numbers for each item.

Use this regex: \d+(?:\.\d+)?.

Related

How can I split a regex into exact words?

I need a little help regarding Regular Expressions in C#
I have the following string
"[[Sender.Name]]\r[[Sender.AdditionalInfo]]\r[[Sender.Street]]\r[[Sender.ZipCode]] [[Sender.Location]]\r[[Sender.Country]]\r"
The string could also contain spaces and theoretically any other characters. So I really need do match the [[words]].
What I need is a text array like this
"[[Sender.Name]]",
"[[Sender.AdditionalInfo]]",
"[[Sender.Street]]",
// ... And so on.
I'm pretty sure that this is perfectly doable with:
var stringArray = Regex.Split(line, #"\[\[+\]\]")
I'm just too stupid to find the correct Regex for the Regex.Split() call.
Anyone here that can tell me the correct Regular Expression to use in my case?
As you can tell I'm not that experienced with RegEx :)
Why dont you split according to "\r"?
and you dont need regex for that just use the standard string function
string[] delimiters = {#"\r"};
string[] split = line.Split(delimiters,StringSplitOptions.None);
Do matching if you want to get the [[..]] block.
Regex rgx = new Regex(#"\[\[.*?\]\]");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);
IDEONE
The regex you are using (\[\[+\]\]) will capture: literal [s 2 or more, then 2 literal ]s.
A regex solution is capturing all the non-[s inside doubled [ and ]s (and the string inside the brackets should not be empty, I guess?), and cast MatchCollection to a list or array (here is an example with a list):
var str = "[[Sender.Name]]\r[[Sender.AdditionalInfo]]\r[[Sender.Street]]\r[[Sender.ZipCode]] [[Sender.Location]]\r[[Sender.Country]]\r";
var rgx22 = new Regex(#"\[\[[^]]+?\]\]");
var res345 = rgx22.Matches(str).Cast<Match>().ToList();
Output:

Regex to get everything after the first space

What would the syntax to get all the words in a string after the first space. For example, bobs nice house. So the result should be " nice house" without the quote.
([^\s]+) gives me all 3 words seperated by ;
,[\s\S]*$ > not compiling.
I was really looking shortest possible code. following did the job. thanks guys
\s(.*)
I think it should be done this way:
[^ ]* (.*)
It allows 0 or more elements that are not a space, than a single space and selects whatever comes after that space.
C# usage
var input = "bobs nice house";
var afterSpace = Regex.Match(input, "[^ ]* (.*)").Groups[1].Value;
afterSpace is "nice house".
To get that first space as well in result string change expression to [^ ]*( .*)
No regex solution
var afterSpace = input.Substring(input.IndexOf(' '));
Actually, you don't need to use regex for that process. You just need to use String.Split() method like this;
string s = "bobs nice house";
string[] s1 = s.Split(' ');
for(int i = 1; i < s1.Length; i++)
Console.WriteLine(s1[i]);
Output will be;
nice
house
Here is a DEMO.
use /(?<=\s).*/g to find string after first space.run snippet check
str="first second third forth fifth";
str=str.match(/(?<=\s).*/g)
console.log(str);

C# - Regular Expression for NO numbers allowed

I want to validate first name and last name from all existing languages.
So I want to validate that there are numbers in a string.
Thanks
[\s\p{L}]
would be the correct character class for this. But of course names can contain many more characters than those (how about Tim O'Reilly or William Henry Gates III.?).
See also Falsehoods Programmers Believe About Names.
Don't even have to use regex:
string tmp = "foo";
var match = tmp.IndexOfAny("0123456789".ToCharArray()) != -1;
Just do !Regex if your validation is in a if statement.
if ( !Regex.Match ( stringToCheck, "^[0-9]+$" ).Success ) {
// TODO.
}
I just tried this one and it should do the trick:
var regex = new Regex(#"[0-9]", RegexOptions.IgnoreCase);
var m = regex.Match(stringValue);
if (m.Success)
//TODO

C# Regular Expression to return only the numbers

Let's say I have the following within my source code, and I want to return only the numbers within the string:
The source is coming from a website, just fyi, and I already have it parsed out so that it comes into the program, but then I need to actually parse these numbers to return what I want. Just having a doosy of a time trying to figure it out tho :(
like: 13|100|0;
How could I write this regex?
var cData = new Array(
"g;13|g;100|g;0",
"g;40|g;100|g;1.37",
"h;43|h;100|h;0",
"h;27|h;100|h;0",
"i;34|i;100|i;0",
"i;39|i;100|i;0",
);
Not sure you actually need regex here.
var str = "g;13|g;100|g;0";
str = str.Replace("g;", "");
would give you "13|100|0".
Or a slight improvement on spinon's answer:
// \- included in case numbers can be negative. Leave it out if not.
Regex.Replace("g;13|g;100|g;0", "[^0-9\|\.\-]", "");
Or an option using split and join:
String.Join("|", "g;13|g;100|g;0".Split('|').Select(pipe => pipe.Split(';')[1]));
I would use something like this so you only keep numbers and separator:
Regex.Replace("g;13|g;100|g;0", "[^0-9|]", "");
Regex might be overkill in this case. Given the uniform delimiting of | and ; I would recommend String.Split(). Then you could either split again or use String.Replace() to get rid of the extra chars (i.e. g;).
It looks like you have a number of solutions, but I'll throw in one more where you can iterate over each group in a match to get the number out if you want.
Regex regexObj = new Regex(#"\w;([\d|.]+)\|?");
Match matchResults = regexObj.Match("g;13|g;100|g;0");
if( matchResults.IsMatch )
{
for (int i = 1; i < matchResults.Groups.Count; i++)
{
Group groupObj = matchResults.Groups[i];
if (groupObj.Success)
{
//groupObj.Value will be the number you want
}
}
}
I hope this is helps.

Helping to make some easy regular exspression

I need reg exspression what make this "123.12312" -> "123.32", or "23.323" -> "23.32" in c#.
It must be only 2 digits after point
:)
Assuming you are parsing a string and it has at least 2 digits after the point:
/[0-9]+\.[0-9]{2}/
I know you are asking about a Regex, but this seems like a better fit for Double.TryParse followed by proper formatting.
Is there a particular reason you need to use Regular Expressions? I would think it'd be better to do something like String.Format("{0:0.00}", double). You can find a list of some helpful formatting examples at http://www.csharp-examples.net/string-format-double/
I don't realy know how regex works in C# but this is my regex
([0-9]+)(?:\.([0-9]{1,2})|)[0-9]*
Group 1 will get the part before the point and group 2 (if exists) will give the part behind the point (2 digits long)
the code here will produce all the matches out of a string:
StringCollection resultList = new StringCollection();
try {
Regex regexObj = new Regex(#"([0-9]+)(?:\.([0-9]{1,2})|)[0-9]*", RegexOptions.Singleline);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
resultList.Add(matchResult.Value);
matchResult = matchResult.NextMatch();
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}

Categories