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

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

Related

Match Characters after last dot in string

I have a string and I want to get the words after the last dot in the string.
Example:
input string = "XimEngine.DynamicGui.PickKind.DropDown";
Result:
DropDown
There's no need in Regex, let's find out the last . and get Substring:
string result = input.Substring(input.LastIndexOf('.') + 1);
If input doesn't have . the entire input will be returned
Not a RegEx answer, but you could do:
var result = input.Split('.').Last();
In Regex you can tell the parser to work from the end of the string/buffer by specifying the option RightToLeft.
By using that we can just specify a forward pattern to find a period (\.) and then capture (using ( )) our text we are interested into group 1 ((\w+)).
var str = "XimEngine.DynamicGui.PickKind.DropDown";
Console.WriteLine(Regex.Match(str,
#"\.(\w+)",
RegexOptions.RightToLeft).Groups[1].Value);
Outputs to console:
DropDown
By working from the other end of the string means we don't have to deal with anything at the beginning of the string to where we need to extract text.

Extract all numbers from string

Let's say I have a string such as 123ad456. I want to make a method that separates the groups of numbers into a list, so then the output will be something like 123,456.
I've tried doing return Regex.Match(str, #"-?\d+").Value;, but that only outputs the first occurrence of a number, so the output would be 123. I also know I can use Regex.Matches, but from my understanding, that would output 123456, not separating the different groups of numbers.
I also see from this page on MSDN that Regex.Match has an overload that takes the string to find a match for and an int as an index at which to search for the match, but I don't see an overload that takes in the above in addition to a parameter for the regex pattern to search for, and the same goes for Regex.Matches.
I guess the approach to use would be to use a for loop of some sort, but I'm not entirely sure what to do. Help would be greatly appreciated.
All you have to to use Matches instead of Match. Then simply iterate over all matches:
string result = "";
foreach (Match match in Regex.Matches(str, #"-?\d+"))
{
result += match.result;
}
You may iterate over string data using foreach and use TryParse to check each character.
foreach (var item in stringData)
{
if (int.TryParse(item.ToString(), out int data))
{
// int data is contained in variable data
}
}
Using a combination of string.Join and Regex.Matches:
string result = string.Join(",", Regex.Matches(str, #"-?\d+").Select(m => m.Value));
string.Join performs better than continually appending to an existing string.
\d+ is the regex for integer numbers;
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, #"\d+").Value;
returns a string with the very first occurence of a number in subjectString.
Int32.Parse(resultString) will then give you the number.

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"

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

Removing digits from a string

When I get the list value from the "Author" column on a list in SharePoint 2010, the following gets displayed:
2;#SP10Setup
Now the user that created that particular list item was "SP10Setup", now is there a simple way to remove "2;#" at the beginning of SP10Setup without affecting the digits in "SP10Setup"?
I have a method that currently is stripping out all digits
//method to strip out unnecessary digits
public static string RemoveDigits(string key)
{
return Regex.Replace(key, #"\d", "");
}
this is how I get the particular list item value:
string author = listItem["Author"].ToString();
this is how I removed unwanted digits and characters:
//calling the RemoveCharacter method
string noDigitsAuthor = RemoveDigits(author);
string cleanedupAuthor = noDigitsAuthor.Replace(";", "").Replace("#", "");
The result I get from this is "SPSetup", but ideally I would want the result to be "SP10Setup".
What would be the quickest and easiest way to achieve this...
Thanks in Advance
You should not do it yourself.
Use SPFieldLookupValue class
String author = "2;#SP10Setup";
SPFieldLookupValue lookup = new SPFieldLookupValue(author);
string cleanedupAuthor = lookup.LookupValue;
int authorId = lookup.LookupId;
so you will have:
cleanedupAuthor = "SP10Setup"
authorId = 2
Use a regular expression like ^\d*;#. The ^ matches the start of the string, \d* says match zero or more digits and ;# are literals.
If your string is always the same length you could use http://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.71%29.aspxenter link description here
first of al ';' and '#' are no digits. but you can take a loot at Removing text in string using Regex

Categories