Replace after a string - Before a character - c#

I have a string like :
string str = "First Option: This is a text. This is second text.";
I can replace This is a text. with :
str = str.Replace("This is a text.", "New text");
But my constant word is First Option: and This is a text is not constant so how can replace the text after First Option: until occurring . (it means before This is second text.).
In this example the expecting result is :
First Option: New text. This is second text.

One option is to use Regex.Replace instead:
str = Regex.Replace(str, #"(?<=First Option:)[^.]*", "New text");
(?<=First Option:)[^.]* matches a sequence of zero or more characters other than dot '.', preceded by First Option: via a positive look-behind.

Not the shortest but if you want to avoid regular expressions:
string replacement = "New Text";
string s = "First Option: This is a text.This is second text.";
string[] parts = s.Split('.');
parts[0] = "First Option: " + replacement;
s = string.Join(".", parts);

Look up .IndexOf() and Substring(...). That will give you what you need:
const string findText = "First Option: ";
var replaceText = "New Text.";
var str = "First Option: This is a text. This is second text.".Replace(findText, "");
var newStr = findText + str.Replace(str.Substring(0, str.IndexOf(".") + 1), replaceText);
Console.WriteLine(newStr);

Related

Regex for only some chars

I have this text:
33113 1;3;\"windlight \"\"Feeling\"\"\r\nmetal, handmade\r\ninside: gold
metallic\r\noutisde: anthracite brushed\r\nH. 14 cm - B. 11,5
cm\";7,95;4001250331131;218,625;262,35;579;21;0004;0001;KUS\r\n
And this regex:
;\\"[^;]*\\";
Which gives the result:
;\"windlight \"\"Feeling\"\"\r\nmetal, handmade\r\ninside: gold metallic\r\noutisde: anthracite brushed\r\nH. 14 cm - B. 11,5 cm\";
Where I like to remove the new-line characters \r\n.Have you any ideas please?
I need something like this:
var replaced = Regex.Replace(
"a regex pattern which removes \r\n from the selected text", " ");
This is what I want to remove from text:
http://postimg.org/image/5hbtd1czx/
So for example,
String str = "Text contains \r \n string here";
str = str.Replace("(\r\n", " "); // with blank space
You can try to use replace:
myString = text.Replace("\r\n", "")
EDIT:
myString = text.Replace(System.Environment.NewLine, " ")
or
myString = text.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ");
Also note that
string[] myString = File.ReadAllLines(yourTextFile);
This will automatically remove all the \n and \r from your text.

How to remove white spaces from sentence?

I want to remove all white spaces from string variable which contains a sentence.
Here is my code:
string s = "This text contains white spaces";
string ns = s.Trim();
Variable "sn" should look like "Thistextcontainswhitespaces", but it doesn't(method s.Trim() isn't working). What am I missing or doing wrong?
The method Trim usually just removes whitespace from the begin and end of a string.
string s = " String surrounded with whitespace ";
string ns = s.Trim();
Will create this string: "String surrounded with whitespace"
To remove all spaces from a string use the Replace method:
string s = "This text contains white spaces";
string ns = s.Replace(" ", "");
This will create this string: "Thistextcontainswhitespaces"
Try this.
s= s.Replace(" ", String.Empty);
Or using Regex
s= Regex.Replace(s, #"\s+", String.Empty);

How to replace the text between two characters in c#

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.

RegEx C# get substring of 12 characters which contains at least one digit AND letter

String testString = "Some text F4LE8AWMF87E and again some text";
Match myMatch = Regex.Match(testString, "\b(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[0-9a-zA-Z]{12,}\b");
myLabel.Text = testString.Substring(myMatch.Index, myMatch.Length);
myLabel should now show "F4LE8AWMF87E" but it doesn't.
What is wrong?
You have to escape the char '\' in a string literal.
String testString = "Some text F4LE8AWMF87E and again some text";
Match myMatch = Regex.Match(testString, #"\b(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[0-9a-zA-Z]{12,}\b");
myLabel.Text = myMatch.Value;
Try the following please:
Reference at Rublar although C# escape makes the slight difference. You can test it out. I believe you if you had to_upper case within the regex, that would make it better :)
String testString = "Some text F4LE8AWMF87 and again some text";
Match myMatch =
Regex.Match(testString, "\b[a-zA-Z\d]{11,12}\b");
myLabel.Text = testString.Substring(myMatch.Index, myMatch.Length);

Replace using regular expression

I would like to make a function that break lines from a string.
eg.: "1. " -> "\n1. "
so i could write a code like this
string Input = "1. First option";
Input += "2. Second option";
Input += "3. Third option";
Output = WriteMenu(Input);
and get a string like this
"1. First option
\n2. Second option
\n3. Third option"
The pattern will always be [number][dot][whitespace].
It's not a problem if the first option came with new line.
Give this guy a shot
Input = Regex.Replace(Input, #"(?<!^)(\d+\.)", "\n$1")
Regex rgx = new Regex("(\\d+\\.\\s)");
String replaced = rgx.Replace(Input, Environment.NewLine + "$1");
A bit shorter expression like this would work too:
Regex.Replace(Input, #"(?!^)\d+\.", "\n$0")

Categories

Resources