I have this method that replaces(in bold) some words in a string and show the changed string in a ritchtextBox.
In the final string I need to replace the # symbol by a newline.
I already tried checked this forum tying several solutions, but nothing worked.
The method I use is
private string bold(string ing)
{
StringBuilder builder = new StringBuilder();
ing = " " + ing + " ";
builder.Append(#"{\rtf1\ansi");
foreach (string word in splitwords)
{
var regex = new Regex(#"(?<![\w])" + word + #"(?![\w])", RegexOptions.IgnoreCase);
ing = regex.Replace(ing, m => #"\b" + m.ToString() + #"\c0");
}
ing = ing.Replace(#"\b", #"\b ");
ing = ing.Replace(#"\c0", #" \b0");
ing = ing.Replace("#", Environment.NewLine);
builder.Append(ing);
builder.Append(#"}");
MessageBox.Show("builder.ToString():" + builder.ToString());
return builder.ToString();
}
When I call the this method and "put it" in the ritchTextBox it doesn´t print the new line
ingred.Rtf = bold(ingd);
How should I solve this??
EDIT:: input string - line1 # line2 # line3
output in the MessageBox
Builder.ToString() : {\rtf1\ansi\b line1\b0
line2
line3
}
output in the ritchTextBox: line1 line2 line3
Instead of
ing = ing.Replace("#", Environment.NewLine);
Try
ing = ing.Replace("#", #"\par\r\n");
Use This Code For Repalce
int startIndex = 0, index;
RichTextBox myRtb = new RichTextBox(); // if have A richtextBox Remove thisline and Use your Richtextbox
myRtb.Rtf = STRRTF;// if have A richtextBox Remove thisline and Use your Richtextbox
while ((index = myRtb.Text.IndexOf("#", startIndex)) != -1)
{
myRtb.Select(index, word.Length);
myRtb.SelectedText ="\n";
startIndex = index + 1;
}
Better use Environment.NewLine for adding new line also Make sure yourRTB.MultiLine property is set to true. assign string to richtext box like this yourRTB.AppendText(t)
Try replacing it with a "\r\n" character sequence?
edit: is MultiLine property of ritchtextBox enabled?
Related
how to split below value and append AND between values ?
I cannot Split with Space as there is spaces between words
"\"Mark John\" \"Tina Roy\""
as
"\"Mark John\" AND \"Tina Roy\""
In the end it should look like -
"Mark John" AND "Tina Roy"
Any help is appreciated.
string operatorValue = " AND ";
if (!string.IsNullOrEmpty(operatorValue))
{
foreach (string searchVal in SearchRequest.Text.Split(' '))
{
if (!string.IsNullOrEmpty(searchVal))
searchValue += searchVal + operatorValue;
}
}
int index = searchValue.LastIndexOf(operatorValue);
if (index != -1)
{
outputSearchValue = searchValue.Substring(0, index);
}
Try
var result = str.Replace("\" \"","\" And \"");
If you have more than one name, or there is a possibility that you could have more than one whitespace between two names, you could opt for Regex.
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Example,
var str = "\"Mark John\" \"Tina Roy\" \"Anu Viswan\"";
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Output
"Mark John" And "Tina Roy" And "Anu Viswan"
Or use Regular Expressions:
var test = "\"John Smith\" \"Bill jones\" \"Bob Norman\"";
Console.WriteLine(Regex.Replace(test, "\" \"", "\" AND \""));
Instead of splitting, replace the " " with " AND "
var test = "\"Mark John\" \"Tina Roy\"";
var new_string= test.Replace("\" \"", " AND ");
I need to insert in a specific position of the string line, another string, so I compute the specific position for start to insert:
string info1 = "info1";
string info2 = "info2";
string info3 = "info3";
string info4 = "info4";
string keyWord = "BELEGIT";
start = line.IndexOf(keyWord, 0) + keyWord.Length + 13;
var aStringBuilder = new StringBuilder(line);
aStringBuilder.Remove(start, 19);
line = aStringBuilder.ToString();
string newLine = line.Insert(start, "\r\n" + info1 + "\r\n" + "\r\n" + info2 + "\r\n" + info3 + "\r\n" + info4 + "\r\n");
(newLine will be the content of a file in my application).
newline contains the correct content except the string "00000" that inserts after "info4". So in my new file with the content that is newline there is newline and immediately after "00000". I do not really understand why.
Thanks in advance.
INPUT:
line contains:
#~11\r\nT-02040121R\r\n\r\n\r\n\r\n\r\n\r\n\n2.000000000\r\n
OUTPUT
newLine contains:
#~11\r\nT-02040121R\r\ninfo1\r\n\r\ninfo2\r\ninfo3\r\ninfo4\r\n00000\r\n
Assuming that you want just the first 19 chars of lineyou could use Substringto get them and string.Formatto build the new string.
Something like this
var start = line.Substring(0, 19);
string newLine = $"{start}\r\n{info1}\r\n\r\n{info2}\r\n{info3}\r\n{info4}\r\n";
The second line is the short form for
string newLine = string.Format("{0}\r\n{1}\r\n\r\n{2}\r\n{3}\r\n{4}\r\n", start, info1, info2, info3, info4);
if you need more information about string.Formathave a look at the MSDN.
I'm trying to replace a string in C# with the class Regex but I don't know use the class properly.
I want replace the next appearance chain in the String "a"
":(one space)(one or more characters)(one space)"
by the next regular expression
":(two spaces)(one or more characters)(three spaces)"
Will anyone help me and give me the code and explains me the regular expresion used?
you can use string.Replace(string, string)
try this one.
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
try this one
private String StrReplace(String Str)
{
String Output = string.Empty;
String re1 = "(:)( )((?:[a-z][a-z]+))( )";
Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(Str);
if (m.Success)
{
String c1 = m.Groups[1].ToString();
String ws1 = m.Groups[2].ToString() + " ";
String word1 = m.Groups[3].ToString();
String ws2 = m.Groups[4].ToString() + " ";
Output = c1.ToString() + ws1.ToString() + word1.ToString() + ws2.ToString() + "\n";
Output = Regex.Replace(Str, re1, Output);
}
return Output;
}
Using String.Replace
var str = "Test string with : .*. to replace";
var newstr = str.Replace(": .*. ", ": .*. ");
Using Regex.Replace
var newstr = Regex.Replace(str,": .*. ", ": .*. ");
I've been trying for the last two hours, but i can't replace the string \n, this is what i did:
Encoding enc = Encoding.ASCII;
for (int i = 0; i < numpntr; i++)
{
bw.BaseStream.Position = strt + i*var;
bw.Write(
enc.GetBytes(listView1.Items[i].SubItems[1].Text.Replace("\n","\x0A") + (new string('\0',
bytecnt - enc.GetByteCount(listView1.Items[i].SubItems[1].Text.Replace("\n" + "\x0A"))))));
}
bw.Flush();
bw.Close();
bw = null;
is there anyway to replace it as a string ?
You could use " \\n " or you can put ' # ' begining of your string like this:
enc.GetBytes(listView1.Items[i].SubItems[1].Text.Replace(#"\n" + "\x0A")
They are called verbatim strings, you can take a look at this documentation.
I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}