I have this code:
string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';
String pattern = #"\s?(\d+)([-])(\d+)";
And I would like to know if there is any way to put the delimiter in the pattern instead of the ([-]) ?
You could use string interpolation:
string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';
String pattern = $#"\s?(\d+)([{delimiter}])(\d+)";
The $ sign (which has to be in front of the #) makes it possible to put a variable (string) in a string by using { }
Note: In older versions of C# however this will not work
In this case you can use string.Format:
string.Format(#"\s?(\d+)([{0}])(\d+)", delimiter);
This works the same way but uses number placeholders for the parameters after the ,
Regex.Escape: (Credits to NtFreX)
Additionally if you are using regex you should escape your character (because they can mean something else in regex).
$#"\s?(\d+)([{Regex.Escape( delimiter.ToString() )}])(\d+)";
This is simplest string concatenation. You have several options:
string concatenation:
Char delimiter = '-';
String pattern = #"\s?(\d+)([" + delimiter + "])(\d+)";
string.Format():
Char delimiter = '-';
String pattern = string.Format(#"\s?(\d+)([{0}])(\d+)", delimiter);
new style Format (only works with newer C# versions):
Char delimiter = '-';
String pattern = $#"\s?(\d+)([{delimiter}])(\d+)";
Additionaly I would use Regex.Escape to escape the delimiter.
$#"\s?(\d+)([{Regex.Escape(delimiter)}])(\d+)";
For example if the delimiter is . it needs to be changed into \. because . is a special regex character which matches any character. The same goas for other characters.
Related
How do I find the uppercase letters of an existing string and add (-) before each of them?
string inputStr = "fhkSGJndjHkjsdA";
string outputStr = String.Concat(inputStr.Where(x => Char.IsUpper(x)));
Console.WriteLine(outputStr);
Console.ReadKey();
This code finds the uppercase letters and prints them on the screen, but I want it to print:
fhk-S-G-Jndj-Hkjsd-A
How can I achieve this?
I think that using a RegEx would be much easier:
string outputStr = Regex.Replace(inputStr, "([A-Z])", "-$1");
Another option using Linq's aggregate:
string inputStr = "fhkSGJndjHkjsdA";
var result = inputStr.Aggregate(new StringBuilder(),
(acc, symbol) =>
{
if (Char.IsUpper(symbol))
{
acc.Append('-');
acc.Append(symbol);
}
else
{
acc.Append(symbol);
}
return acc;
}).ToString();
Console.WriteLine(result);
Using Where Filters a sequence of values based on a predicate and then String.Concat will concatenate all the values giving you SGJHA.
Instead, you could use Select, check per character for an uppercase char and return the char prepended with a - or the same char as a string when not an uppercase char.
string inputStr = "fhkSGJndjHkjsdA";
String outputStr = String.Concat(inputStr.Select(c => Char.IsUpper(c) ? "-" + c : c.ToString()));
Console.WriteLine(outputStr);
Output
fhk-S-G-Jndj-Hkjsd-A
C# demo
To also find unicode uppercase characters using a regex, you could use \p{Lu} to find an uppercase letter that has a lowercase variant as Char.IsUpper checks for a Unicode character.
In the replacement, you can use the full match using $0 prepended with a -
string inputStr = "fhkSGJndjHkjsdA";
string outputStr = Regex.Replace(inputStr, #"\p{Lu}", "-$0");
Console.WriteLine(outputStr);
Output
fhk-S-G-Jndj-Hkjsd-A
C# demo
Hi there I have this
string s = #"A:\"
And i have to change the letter, so i need this
string s= #" + Letter + :\"
I already tried something, but it was lame...
Try this:
string s = Letter + #":\";
If you're using C# 6.0, you could use interpolated strings. (but you need to escape the \)
string s = $"{Letter}:\\";
You either need to escape the backslash, because it's a special character, by using two backslashes, like this:
string s = Letter + ":\\"
or you need to indicate that the string with the backslash should be interpreted "verbatim" by putting an # in front of it, like this:
string s = Letter + #":\"
You can use string format to help. There is also string interpolation if you are using c# 6.0.
var Letter = "A";
string s = string.Format(#"{0}:\", Letter);
String interpolation with c# 6.0
string s = $"{Letter}:\\";
In c#, I want use a regular expression to replace each variable #A with a number withouth replacing other similar variables like #AB
string input = "3*#A+3*#AB/#A";
string value = "5";
string pattern = "#A"; //<- this doesn't work
string result = Regex.Replace(input, pattern, value);
// espected result = "3*5+3*#AB/5"
any good idea?
Use a word boundary \b:
string pattern = #"#A\b";
See regex demo (Context tab)
Note the # before the string literal: I am using a verbatim string literal to declare the regex pattern so that I do not have to escape the \. Otherwise, it would look like string pattern = "#A\\b";.
I need a c# function which will replace all special characters customized by the client from a string Example
string value1 = #"‹¥ó׬¶ÝÆ";
string input1 = #"Thi¥s is\123a strÆing";
string output1 = Regex.Replace(input1, value1, "");
I want have a result like this : output1 =Thi s is\123a str ing
Why do you need regex? This is more efficient, concise also readable:
string result = string.Concat(input1.Except(value1));
If you don't want to remove but replace them with a different string you can still use a similar(but not as efficient) approach:
string replacement = "[foo]";
var newChars = input1.SelectMany(c => value1.Contains(c) ? replacement : c.ToString());
string result = string.Concat( newChars ); // Thi[foo]s is\123a str[foo]ing
Someone asked for a regex?
string value1 = #"^\-[]‹¥ó׬¶ÝÆ";
string input1 = #"T-^\hi¥s is\123a strÆing";
// Handles ]^-\ by escaping them
string value1b = Regex.Replace(value1, #"([\]\^\-\\])", #"\$1");
// Creates a [...] regex and uses it
string input1b = Regex.Replace(input1, "[" + value1b + "]", " ");
The basic idea is to use a [...] regex. But first you have to escape some characters that have special meaning inside a [...]. They should be ]^-\ Note that you don't need to escape the [
note that this solution isn't compatible with non-BMP unicode characters (characters that fill-up two char)
A solution that is compatible with them is more complex, but for normal use it shouldn't be a problem.
I am bit confused writing the regex for finding the Text between the two delimiters { } and replace the text with another text in c#,how to replace?
I tried this.
StreamReader sr = new StreamReader(#"C:abc.txt");
string line;
line = sr.ReadLine();
while (line != null)
{
if (line.StartsWith("<"))
{
if (line.IndexOf('{') == 29)
{
string s = line;
int start = s.IndexOf("{");
int end = s.IndexOf("}");
string result = s.Substring(start+1, end - start - 1);
}
}
//write the lie to console window
Console.Write Line(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
I want replace the found text(result) with another text.
Use Regex with pattern: \{([^\}]+)\}
Regex yourRegex = new Regex(#"\{([^\}]+)\}");
string result = yourRegex.Replace(yourString, "anyReplacement");
string s = "data{value here} data";
int start = s.IndexOf("{");
int end = s.IndexOf("}", start);
string result = s.Substring(start+1, end - start - 1);
s = s.Replace(result, "your replacement value");
To get the string between the parentheses to be replaced, use the Regex pattern
string errString = "This {match here} uses 3 other {match here} to {match here} the {match here}ation";
string toReplace = Regex.Match(errString, #"\{([^\}]+)\}").Groups[1].Value;
Console.WriteLine(toReplace); // prints 'match here'
To then replace the text found you can simply use the Replace method as follows:
string correctString = errString.Replace(toReplace, "document");
Explanation of the Regex pattern:
\{ # Escaped curly parentheses, means "starts with a '{' character"
( # Parentheses in a regex mean "put (capture) the stuff
# in between into the Groups array"
[^}] # Any character that is not a '}' character
* # Zero or more occurrences of the aforementioned "non '}' char"
) # Close the capturing group
\} # "Ends with a '}' character"
The following regular expression will match the criteria you specified:
string pattern = #"^(\<.{27})(\{[^}]*\})(.*)";
The following would perform a replace:
string result = Regex.Replace(input, pattern, "$1 REPLACE $3");
For the input: "<012345678901234567890123456{sdfsdfsdf}sadfsdf" this gives the output "<012345678901234567890123456 REPLACE sadfsdf"
You need two calls to Substring(), rather than one: One to get textBefore, the other to get textAfter, and then you concatenate those with your replacement.
int start = s.IndexOf("{");
int end = s.IndexOf("}");
//I skip the check that end is valid too avoid clutter
string textBefore = s.Substring(0, start);
string textAfter = s.Substring(end+1);
string replacedText = textBefore + newText + textAfter;
If you want to keep the braces, you need a small adjustment:
int start = s.IndexOf("{");
int end = s.IndexOf("}");
string textBefore = s.Substring(0, start-1);
string textAfter = s.Substring(end);
string replacedText = textBefore + newText + textAfter;
the simplest way is to use split method if you want to avoid any regex .. this is an aproach :
string s = "sometext {getthis}";
string result= s.Split(new char[] { '{', '}' })[1];
You can use the Regex expression that some others have already posted, or you can use a more advanced Regex that uses balancing groups to make sure the opening { is balanced by a closing }.
That expression is then (?<BRACE>\{)([^\}]*)(?<-BRACE>\})
You can test this expression online at RegexHero.
You simply match your input string with this Regex pattern, then use the replace methods of Regex, for instance:
var result = Regex.Replace(input, "(?<BRACE>\{)([^\}]*)(?<-BRACE>\})", textToReplaceWith);
For more C# Regex Replace examples, see http://www.dotnetperls.com/regex-replace.