I have string file with content like this
string a = "12,1,______,_,__;1,23,122;"
I want to grab only this integer value 23. Problem is that this conntent is dynamic and I it's lenght can be changed, so this string a can easily be in the next iteration like
string a = "12,1,______,_,__;11,2,1;"
In this case I would grab integer 2.
If the structure is always the same, then:
Split the string, and grab the element before last.
var array1 = a.Split(';');
// check the array length if it's needed to avoid
// IndexOutOfRangeException exception
var array2 = array1[1].Split(',');
var yourNumber = array2[array2.Length - 2]
String.Split
Ignoring error checking for a minute, this would work:
string a = "12,1,______,_,__;11,2,1;"
int i = Int32.Parse(String.Split(',')[5])
If this is the route you will go, you should take extra care to verify your input. Check the length of the array reutrned from Split, and verify that the 5th value can indeed be parsed to an int.
Try this regex:
(?<=;\d*,)\d*(?=,\d*;)
Sample usage:
class Program
{
static void Main(string[] args)
{
string a = "12,1,______,_,__;1,23,122;";
var regex = new Regex(#"(?<=;\d*,)\d*(?=,\d*;)");
Console.WriteLine(regex.Match(a).Value);
a = "12,1,______,_,__;11,2,1;";
Console.WriteLine(regex.Match(a).Value);
}
}
Try this:
var number = a.split(",")[5];
another option is to split the text into array (if they have same pattern):
var output = a.Split(",;".ToCharArray());
var value = output[theIndex]; // get the index you want
Related
I've got a program that reads .HRM files and I'm wanting it to search through the text file and retrieve the integer value after whatever it states. I have it reading the text file for other things, I just can't figure this one out. As below for example:
if (line.Contains("Version="))
{
//Get the integer after 'Version='
}
I am not too sure how to get this integer value and store it.
The HRM file reads as below:
[Params]
Version=106
Monitor=34
SMode=111111100
Date=20130205
StartTime=15:46:20.0
Length=01:06:18.9
Interval=1
Upper1=0
Lower1=0
Upper2=0
Lower2=0
Upper3=180
Lower3=170
Timer1=00:00:00.0
Timer2=00:00:00.0
After you find that the line contains Version=
var number = int.Parse(line.Split('=')[1]);
how about
int Version = int.Parse(line.Split('=')[1]);
var versionNumber = int.Parse(line.Replace("Version=", string.Empty));
Or you could do RegEx and so on.
You could use the string methods IndexOf and Substring, for example with this LINQ query:
IEnumerable<String> versions =
from line in File.ReadAllLines(#"filename.HRM") // go through all the lines
let index = line.IndexOf("Version=") // returns -1 if the line doesn't contain "Version="
where index >= 0 // return also those which contain it
select line.Substring(index + "Version=".Length); // return just the version after the '=' sign
foreach (string version in versions)
Console.WriteLine(version);
If you expect only one you could also use string version = versions.FirstOrDefault();
If you want to convert it to int use int.Parse.
If you want to be able to extract just the numbers from any string you would use this:
int versionNumber = int.Parse(Regex.Match(line, #"\d+").Value);
I am trying to extract only numbers from a text file in c#. My text file is like as below
xasd 50 ysd 20 zaf 40 bhar 60
I am trying to browse a file with openfileDialoug and read that file and extract the numbers from the same file and need to compare those values with a constant value say 60. I need to display how many numbers are present more than that constant number. If those numbers are greater than 60 then i need to append the number of greater values to richtextBox along with the existing text.
You can use the Int32.TryParse(string s,out int result) method. It returns true if the string s can be parsed as an integer and stores the value in int result. Also, you can use the String.Split(Char[]) method to split the line you read from Text File.
string line = fileObject.ReadLine();
int constant = 60; //For your example
int num = 0;
string []tokens = line.Split(); //No arguments in this method means space is used as the delimeter
foreach(string s in tokens)
{
if(Int32.TryParse(s, out num)
{
if(num > constant)
{
//Logic to append to Rich Text Box
}
}
}
Regex is an elegant way to find numbers in a string which is the OP requirement, something like:
string allDetails = File.ReadAllText(Path);
result = Regex.Match(allDetails, #"\d+").Value;
Now the resultString will contain all the extracted integers
In case you want to take care of negative numbers too=, then do this modification
result = Regex.Match(allDetails, #"-?\d+").Value;
Hope this helps, check out the following post:
Find and extract a number from a string
If your file is always like as you have shown then you can easily split it and parse:
string filePath = ""; // from OpenFileDialog
string fileContents = File.ReadAllText(filePath);
string[] values = fileContents.Split();
int valueInt, greaterValuesCount = 0;
foreach (var value in values)
{
if (int.TryParse(value, out valueInt))
{
greaterValueCount++;
// Do something else here
}
}
So, basically what i need is to get numbers that are between second and third dot.
Example:
I type in my textbox "1.1.1.1" or "183.312.21.132", I click a button and in the seconds textbox I get numbers that are between second and third dot. Like for first one it would be "1" and for seconds one it will be "21"
Sorry for bad English. Thanks!
try split
"1.1.1.1".Split('.')[2]
or
"183.312.21.132".Split('.')[2]
returns a string[] and index 2 would be the third number
Use string split:
"183.312.21.132".Split(".")[index_of_the_dot_before_desired_numbers]
i.e.
"183.312.21.132".Split('.')[2] = "21"
UPD:
if you need a range between dots, you can use LINQ:
var startDotIndex=1;
var endDotIndex=3;
"183.312.21.132".Split('.').Skip(startDotIndex).Take(endDotIndex-startDotIndex).ToArray()
will return ["312", "21"];
string digits[] = "1.2.3.4".Split(".");
Use elsewhere with:
digits[0]
digits[1]
It sounds like you need the String object's Split method see below:
string foo = "183.312.21.132";
string[] foos = foo.Split('.');
from here you can do many different things such as loop through your array and grab values or if you know exactly what index you are looking for you can simply request it straight from the array such as:
string bar = foo.Split('.')[2]; // gives you "21"
var foo = "192.168.0.1";
var digs = foo.Split(".");
var nums = int.Parse(digs[2]);
I want to get only number id from string. result : 123456
var text = "http://test/test.aspx?id=123456dfblablalab";
EDIT:
Sorry, Another number can be in the text. I want to get first number after id.
var text = "http://test/test.aspx?id=123456dfbl4564dsf";
Use:
Regex.Match(text, #"id=(\d+)").Groups[1].Value;
It depends on the context - in this case it looks like you are parsing a Uri and a query string:
var text = "http://test/test.aspx?id=123456dfblablalab";
Uri tempUri = new Uri(text);
NameValueCollection query = HttpUtility.ParseQueryString(tempUri.Query);
int number = int.Parse(new string(query["id"].TakeWhile(char.IsNumber).ToArray()));
Someone will give you a C# implementation, but it's along the lines of
/[\?\&]id\=([0-9]+)/
Which will match either &id=123456fkhkghkf or ?id=123456fjgjdfgj (so it'll get the value wherever it is in the URL) and capture the number as a match.
I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"