Regular expression (getting number, C#) - c#

Please help me to write Regular expression on C# for getting Int64 value from string:
"NumberLong("634461051992965873")"
my string includes NumberLong part;
so as result must be 634461051992965873
Thank you!)))

string Temp = "Hax00r L33t";
string Output = Regex.Replace(Temp, "[^0-9]", "");
long num = long.Parse(Output);

long.Parse("634461051992965873")
does the job, but you could check long.TryParse too.

String txt = "634461051992965873";
int nbr;
if(Int64.TryParse(txt, out nbr)) {
// text can be converted to Integer
}

Related

How to get text until a symbol in string

How to get text before a symbol in string ? Any ideas?
e.g. acsbkjb/123kbvh/123jh/
get text before first - "/"
Try this
string ss = myString.Split('/')[0];
You can use Substring() method to get the required part of the string.
String text="acsbkjb/123kbvh/123jh/";
int index=text.IndexOf('/');
String text2="";
if(index>=0)
text2=text.Substring(0,index);
get substring like
youstring.Substring(0,yourstring.IndexOf('/'));
The IEnumerable approach
string str = "acsbkjb/123kbvh/123jh/";
var result = new string(str.TakeWhile(a => a != '/').ToArray());
Console.WriteLine(result);
If there are no forward slashes this works without need to check the return of IndexOf
EDIT Keep this answer just as an example because the efficiency of this approach is really worse. IndexOf works faster also if you add an if statement to check the return value.
string text = "acsbkjb/123kbvh/123jh/";
string text2 = text.Substring(0, text.IndexOf("/"));

How to convert a string with a period character to an int?

How do you convert a string with a period character to an int?
I have to convert strings like "1924.912" to int's, but the int.Parse() and Convert.ToInt32() methods don't work here.
Try this:
var str = "1924.912";
var mass = str.Split('.').Select(x => x).ToArray();
Or this:
var str = "1924.912";
var mass = str.Split('.');
To have all decimal like int use next:
var str = "1924.912";
var mass = str.Replace(".","");
You can use Double.Parse() and then convert result to int.
var result = (int)Double.Parse("1924.912");
Optionally you can specify decimal separator because its local specific.
If you want get 1924912 from "1924.912" you can achieve this by replacing "." by "":
string s = "1924.912";
int result = int.Parse(s.Replace(".", ""));
result.Dump();
Will print 1924912.
Do this
string value = "34690.42724";
Convert.ToInt64(Math.Round(Convert.ToDouble(value)));
double.Parse(textBox1.Text.Replace(".",","))
If you want to convert the string "1924.912" to the integer 1924912 disregarding the period you can use this expression where you simply remove any periods in the string before doing the conversion:
Int32.Parse("1924.912".Replace(".", String.Empty))

Formatting values

Hi i have a int example as 3 i need to format it as 003 . is the only way is convert to a string and concat and convert back ?
I guess this is what you want:
int n = 3;
string formatted = n.ToString("000");
Alternatively:
string formatted = String.Format("{0:000}", n);
More info here.
You can apply the .ToString("000"); method.
Debug.WriteLine(3.ToString("000"));
You can parse the resulting string value by using int.Parse or int.TryParse:
Debug.WriteLine(int.Parse("003"));
See Custom Numeric Format Strings
If it's an int object, the leading zeros will always be removed, regardless if you convert it to a string and back.
use the pad functionint i = 1;
i.ToString().PadLeft(3, '0');

string manipulation check and replace with fastest method

I have some strings like below:
string num1 = "D123_1";
string num2 = "D123_2";
string num3 = "D456_11";
string num4 = "D456_22";
string num5 = "D_123_D";
string num5 = "_D_123";
I want to make a function that will do the following actions:
1- Checks if given string DOES HAVE an Underscore in it, and this underscore should be after some Numbers and Follow with some numbers: in this case 'num5' and 'num6' are invalid!
2- Replace the numbers after the last underscore with any desired string, for example I want 'num1 = "D123_1"' to be changed into 'D123_2'
So far I came with this idea but it is not working :( First I dont know how to check for criteria 1 and second the replace statement is not working:
private string CheckAndReplace(string given, string toAdd)
{
var changedString = given.Split('_');
return changedString[changedString.Length - 1] + toAdd;
}
Any help and tips will be appriciated
What you are looking for is a regular expression. This is (mostly) from the top of my head. But it should easily point you in the right direction. The regular expression works fine.
public static Regex regex = new Regex("(?<character>[a-zA-Z]+)(?<major>\\d+)_(?<minor>\\d+)",RegexOptions.CultureInvariant | RegexOptions.Compiled);
Match m = regex.Match(InputText);
if (m.Succes)
{
var newValue = String.Format("{0}{1}_{2}"m.Groups["character"].Value, m.Groups["major"].Value, m.Groups["minor"].Value);
}
In your code you split the String into an array of strings and then access the wrong index of the array, so it isn't doing what you want.
Try working with a substring instead. Find the index of the last '_' and then get the substring:
private string CheckAndReplace(string given, string toAdd) {
int index = given.LastIndexOf('_')+1;
return given.Substring(0,index) + toAdd;
}
But before that check the validity of the string (see other answers). This code fragment will break when there's no '_' in the string.
You could use a regular expression (this is not a complete implementation, only a hint):
private string CheckAndReplace(string given, string toAdd)
{
Regex regex = new Regex("([A-Z]*[0-9]+_)[0-9]+");
if (regex.IsMatch(given))
{
return string.Concat(regex.Match(given).Groups[1].Value, toAdd);
}
else
{
... do something else
}
}
Use a good regular expression implementation. .NET has standard implementation of them

using numbers in a string

Can I use numbers while using String data type?
Sure you can, and if you want to use them as numbers you can parse the string. E.g. for an integer:
string numberAsString = "42";
int numberFromString;
if (int.TryParse(numberAsString, out numberFromString))
{
// number successfully parsed from string
}
TryParse will return a bool telling if the parsing were successful. You can also parse directly if you know the string contains a number - using Parse. This will throw if the string can't be parsed.
int number = int.Parse("42");
You can have numbers in a string.
string s = "123";
..but + will concatenate strings:
string s = "123";
string other = "4";
Debug.Assert(s + other != "127");
Debug.Assert(s + other == "1234");
Numbers can be easily represented in a string:
string str = "10";
string str = "01";
string str = 9.ToString();
However, these are strings and cannot be used as numbers directly, you can't use arithmetic operations on them and expect it to work:
"10" + "10"; // Becomes "1010"
"10" / "10"; // Will not compile
You can easily store numbers as a string:
string foo = "123";
but that only helps you if you actually want numbers in a string. For arithmetic purposes, use a number. If you need to display that later, us a format string.
String number1 = "123456";
keep in mind. using that number for arithmatic purpose, you have to convert that string into proper type like
int number1Converted = Int32.Parse(number1);
int.TryParse(number1 , out number1Converted );
for double
double doubleResult = 0.0;
double.TryParse("123.00", out doubleResult);

Categories