Replace word between two sets of brackets - c#

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];
});

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"

Replacing the character between angle brackets

Story:
I have a list box that shows all the methods of the current application. I need to colorize the method parameters' data type to blue.
Solution: FIRST, I extract the content between the parenthesis. SECOND, I want to split them by COMMA
Problem:
If the arguments entail something like IDictionary<string, string> which occurs multiple times, then the above solution faces problem!! Thus, I decided to FIRST grab all the content between the angle brackets and then Replace their comma with "#COMMA#" and after performing the task using the above solution simply replace the "#COMMA#" with ",". BUT, based on the solution found HERE, it is not possible to set any value to match.value. Here is my code:
if (methodArgumentType.Contains("<") && methodArgumentType.Contains(">"))
{
var regex = new Regex("(?<=<).*?(?=>)");
foreach (Match match in regex.Matches(methodArgumentType))
{
match.Value = match.Value.Replace(",", "#COMMA#");
}
}
Any suggestion highly appreciated.
You need to replace the matched value inside the match evaluator within Regex.Replace:
var methodArgumentType = "IDictionary<string, string>";
if (methodArgumentType.Contains("<") && methodArgumentType.Contains(">"))
{
methodArgumentType = Regex.Replace(methodArgumentType, #"<([^<>]+)>",
m => string.Format("<{0}>", m.Groups[1].Value.Replace(",", "#COMMA#")));
}
Console.WriteLine(methodArgumentType);
// => IDictionary<string#COMMA# string>
Here, m.Groups[1].Value will hold string, string and the replacement will be done on the input string itself, not the Regex.Match object.

Regex replacing inside of

Well, I have this code:
StreamReader sr = new StreamReader(#"main.cl", true);
String str = sr.ReadToEnd();
Regex r = new Regex(#"&");
string[] line = r.Split(str);
foreach (string val in line)
{
string Change = val.Replace("puts","System.Console.WriteLine()");
Console.Write(Change);
}
As you can see, I'm trying to replace puts (content) by Console.WriteLine(content) but it would be need Regular Expressions and I didn't found a good article about how to do THIS.
Basically, taking * as the value that is coming, I'd like to do this:
string Change = val.Replace("puts *","System.Console.WriteLine(*)");
Then, if I receive:
puts "Hello World";
I want to get:
System.Console.WriteLine("Hello World");
You need to use Regex.Replace to capture part of the input by using a capturing group and include the captured match into the output. Example:
Regex.Replace(
"puts 'foo'", // input
"puts (.*)", // .* means "any number of characters"
"System.Console.WriteLine($1)") // $1 stands for whatever (.*) matched
If the input always ends in a semicolon you would want to move that semicolon outside the WriteLine parens. One way to do that is:
Regex.Replace(
"puts 'foo';", // input
"puts (.*);", // ; outside parens -- now it's not captured
"System.Console.WriteLine($1);") // manually adding the fixed ; at the end
If you intend to adapt these examples it's a good idea to consult a technical reference first; you can find a very good one here.
What you want to do is look at Grouping Expressions. Give the following a try
Regex.Replace(val, "puts (.*);", "System.Console.WriteLine(${1});");
Note that you can also name your groups, as opposed to using their indexes for replacement. You can do this like so:
Regex.Replace(val, "puts (?<str>.*);", "System.Console.WriteLine(${str});");

Extract all values between { dynamic } and place in a string array

I need to extract all words between { } brackets and place in a string array.
The problem is that the text between the brackets is dynamic.
For example:
Hi {name}, thanks for visiting {site}
In this text i want to get name and site words place in a array.
Thanks!
Solution : you can use Substring() function to retrieve the part of the string.
Syntax: Substring(int startindex,int length);
Steps:
1. you need to send the starting index(1) of { to Substring() function as first parameter.
2. you need to send the length of string to be retrieved that means index(2) of } in the form of length (index2-index1) to Substring() function as second parameter.
Try this:
String middlevalue="";
String str = "thanks for visiting {site}";
int index1= str.IndexOf("{");
index1++;
int index2=str.IndexOf("}");
if(index1!=-1 && index2!=-1)
middlevalue=str.Substring(index1, (index2 - index1)));
Output:
middlevalue contains -> site
Regex should work for you, note that all the words between {...} should not contain any {...}.
var items = Regex.Matches(input, "\{[^{]+\}").Cast<Match>()
.Select(m=>m.Value.Trim('{','}')).ToArray();
Adding to King's answer, this will help you retrieve just the keys without surrounding brackets.
Regex.Matches(input, #"\{(?<Value>[^{]+)\}").Cast<Match>()
.Select(m=>m.Groups["Value"].Value).ToArray();
Try this:
var regex = #"(?<=\{)[^}]*(?=\})";
var text = "Hello my name is {James}";
var matches = Regex.Matches(text, regex);

Parse value from string with structure "key=value"

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

Categories