Parse value from string with structure "key=value" - c#

I have a string like this:
SUBJECT=Some text here\r\n
VALUE=19355711\r\n
RCV_VALUE=2851404175\r\n
RESULT=1\r\n
CNCODE=0\r\n
KEY1=1\r\n
KEY2=2
Now I need to get the values of RCV_VALUE and RESULT from this string. The position of these keys in the string may vary. They can also be at the beginning or/and at the end of the string.
Value of RESULT I must get as int, and value of RCV_VALUE I must get as string.
What is the best way to get the values of these keys regardless of their position in the string?

Best bet is a regular expression
var regex=new Regex(#"RCV_VALUE=(?<value>\d+)");
var match=regex.Match(inputString);
var rcv_value=int.Parse(match.Groups["value"].Value);

You can achieve this using an regular expression easily enough, as per the example below.
Regex expr = new Regex(#"^(?<Key>.*)=(?<Value>.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var m = expr.Match("SUBJECT=Some text here\r\n");
var key = m.Groups["Key"].Value;
var value = m.Groups["Value"].Value;
// or
var kvp = new KeyValuePair<string, string>(m.Groups["Key"].Value, m.Groups["Value"].Value);
Or alternatively if you do not want to use a regular expression you can split the string using the = as a delimiter and then parse the values in pairs.

Use string spilt to split it into multiple lines, and then loop over the array. After this i would use indexof and either substring or string remove to get the parts i want.
This all being said, this questions smells of "do my work for me". I would recommend going to www.codeproject.com and learn the basics.

Try
var RCV_VALUE = Regex.Match(myString, "RCV_VALUE=(\d+)").Groups[1].Value

Related

Extracting only the substring containing letters from a string containing digits strings and symbols

I have a string that is like the following:
string str = hello_16_0_2016;
What I want is to extract hello from the string. As in my program the string part can occur anywhere as it is autogenerated, so I cannot fix the position of my string.
For example: I can take the first five string from above and store it in a new variable.
But as occurring of letters is random and I want to extract only letters from the string above, so can someone guide me to the correct procedure to do this?
Could you just use a simple regular expression to pull out only alphabetic characters, assuming you only need a-z?
using System.Text.RegularExpressions;
var str = "hello_16_0_2016";
var onlyLetters = Regex.Replace(str, #"[^a-zA-Z]", "");
// onlyLetters = "hello"
I'd use something like this (uses Linq):
var str = "hello_16_0_2016";
var result = string.Concat(str.Where(char.IsLetter));
Check it out
Or, if performance is a concern (because you have to do this on a tight loop, or have to convert hundreds of thousands of strings), it'd probably be faster to do:
var result = new string(str.Where(char.IsLetter).ToArray());
Check it too
But as occurring of letters is random and I want to extract only
letters from the string above, so can someone guide me to the correct
procedure to do this?
The following will extract the first text, without numbers anywhere in the string:
Console.WriteLine( Regex.Match("hello_16_0_2016", #"[A-Za-z]+").Value ); // "hello"

Using regex to remove everything that is not in between '<#'something'#>' and replace it with commas

I have a string, for example
<#String1#> + <#String2#> , <#String3#> --<#String4#>
And I want to use regex/string manipulation to get the following result:
<#String1#>,<#String2#>,<#String3#>,<#String4#>
I don't really have any experience doing this, any tips?
There are multiple ways to do something like this, and it depends on exactly what you need. However, if you want to use a single regex operation to do it, and you only want to fix stuff that comes between the bracketed strings, then you could do this:
string input = "<#String1#> + <#String2#> , <#String3#> --<#String4#>";
string pattern = "(?<=>)[^<>]+(?=<)";
string replacement = ",";
string result = Regex.Replace(input, pattern, replacement);
The pattern uses [^<>]+ to match any non-pointy-bracket characters, but it combines it with a look-behind statement ((?<=>)) and a look-ahead statement (?=<) to make sure that it only matches text that occurs between a closing and another opening set of brackets.
If you need to remove text that comes before the first < or after the last >, or if you find the look-around statements confusing, you may want to consider simply matching the text that comes between the brackets and then loop through all the matches and build a new string yourself, rather than using the RegEx.Replace method. For instance:
string input = "sdfg<#String1#> + <#String2#> , <#String3#> --<#String4#>ag";
string pattern = #"<[^<>]+>";
List<String> values = new List<string>();
foreach (Match m in Regex.Matches(input, pattern))
values.Add(m.Value);
string result = String.Join(",", values);
Or, the same thing using LINQ:
string input = "sdfg<#String1#> + <#String2#> , <#String3#> --<#String4#>ag";
string pattern = #"<[^<>]+>";
string result = String.Join(",", Regex.Matches(input, pattern).Cast<Match>().Select(x => x.Value));
If you're just after string manipulation and don't necessarily need a regex, you could simply use the string.Replace method.
yourString = yourString.Replace("#> + <#", "#>,<#");

Replace word between two sets of brackets

I have a string:
"You have just received {{PowerUpName}} from {{PlayerName}}"
I then receive a set of parameters (in JSON format):
{"PowerUpName":"Super Boost","PlayerName":"John"}
I'm trying to work out how I replace the words within double brackets i.e. {{PowerUpName}} with a parameter. I guess I need to use regex but I have no idea what the expression should be. I'm coding in C# by the way (and can't use LINQ).
Any help would be much appreciated.
If the string "You have just received {{PowerUpName}} from {{PlayerName}}" is always the same you don't need regex.
You can simply use the String.Replace method for every parameter from JSON.
If you want to replace any words inside {{ and }} symbols, you do not need LINQ:
// Input string
string str = "You have just received {{PowerUpName}} from {{PlayerName}}";
// Initializing sample dictionary object
var obj = new Dictionary<string,string>();
// Filling it out
obj.Add("PowerUpName", "Super Boost");
obj.Add("PlayerName", "John");
// Replacing the values with those in the dictionary
string output = Regex.Replace(str, "(?<=\\{\\{)(.*?)(?=\\}\\})", match => obj[match.Groups[1].Value]);
// Display result
Console.WriteLine(output);
Result:
You have just received {{Super Boost}} from {{John}}
Provided that the brackets are correctly matched and there are no nested brackets, you can do this
var obj = {"PowerUpName":"Super Boost","PlayerName":"John"};
Regex.Replace(input, #"(?<=\{\{.*?(?=\}\})", delegate(match){
return obj[match];
});

How to cut rest of string after substring in c#?

I got a string like this (my readline):
alfa: 10662 beta: -64 gama: 70679 delta: 1001
I need to use some of this numbers as a parameters but these numbers can have varying length. I can imagine that extracting value alfa I can do with:
str1 = readline.Substring(6, 5);
But how would I get the value of gamma if the values of beta and alpha can vary?
You can use a regex to match all the name:value pairs and use capture groups to extract the names and values:
var readline = "alpha: 10662 beta: -64 gamma: 70679 delta: 1001";
var matches = Regex.Matches(readline, #"(?<parameter>\w*):\s*(?<value>-?\d*)");
var dictionary = new Dictionary<string,int>();
foreach (Match m in matches)
{
dictionary.Add(m.Groups["parameter"].Value,int.Parse(m.Groups["value"].Value));
}
Console.WriteLine(dictionary["gamma"]); // output: 70679
I would go about doing it a different way that using substring. First, split on the separators to produce an array of keys/values with the keys in the even positions and the values in the odd positions. Then you can either iterate through the array by 2s choosing the value associated with key desired or, if they are always in the same order, just choose the correct array element to convert.
Apply input validation as needed to make sure you don't have corrupt inputs.
var parameters = line.Split( new [] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries );
for (var i = 0; i < parameters.Length; i += 2 )
{
var key = parameters[i];
var value = int.Parse( parameters[i+1] );
// do something with the value based on the key
}
It seems like a good fit for a regular expression:
var regex = new Regex(#"(\w+)\:\s(-?\d+)");
var values = from pair in regex.Matches("alfa: 10662 beta: -64 gama: 70679 delta: 1001").OfType<Match>()
select new { Key = pair.Groups[1].Value, pair.Groups[2].Value };
I wouldn't use SubString for this; it will be more verbose and error prone.
At it's simplest, it looks as though all of your data is separated by whitespace. Is this a fair assumption? Is the order of each variable always the same? If so, then you can simply split on whitespace and grab every other number;
If the data is not always of the same form, then I would use a regular expression instead. You can use something of the form:
/alfa: ([+-]\d+)/
Which will capture the number after "alpha:" and the sign. You will need something a bit fancier for floating point values. Honestly, I very rarely use regular expressions, and when I write a non-trivial regex I always use regex buddy, so I don't want to write a comprehensive one here for you as it will take me too long =)
EDIT: See, Mark's Regex is much better than mine.

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.

Categories