I have a string like this:
“I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”
I want to insert <strong> around the "a" in "a diplomatic", but nowhere else.
What I have as input is diplomatic from a previous function, and I wan't to add <strong>to the closest instance of "a".
Right now, of course when I use .Replace("a", "<strong>a</strong>"), every single instance of "a" receives the <strong>-treatment, but is there any way to apply this to just to one I want?
Edit
The string and word/char ("a" in the case above) could be anything, as I'm looping through a lot of these, so the solution has to be dynamic.
var stringyourusing = "";
var letter = "";
var regex = new Regex(Regex.Escape(letter));
var newText = regex.Replace(stringyourusing , "<strong>letter</strong>", 1);
Would this suffice?
string MakeStrongBefore(string strong, string before, string s)
{
return s.Replace(strong + " " + subject, "<strong>" + strong + "</strong> " + before);
}
Used like this:
string s = “I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”;
string bolded = MakeStrongBefore("a", "diplomatic", s);
Try this:
public string BoldBeforeString(string source, string bolded,
int boldBeforePosition)
{
string beforeSelected = source.Substring(0, boldBeforePosition).TrimEnd();
int testedWordStartIndex = beforeSelected.LastIndexOf(' ') + 1;
string boldedString;
if (beforeSelected.Substring(testedWordStartIndex).Equals(bolded))
{
boldedString = source.Substring(0, testedWordStartIndex) +
"<strong>" + bolded + "</strong>" +
source.Substring(testedWordStartIndex + bolded.Length);
}
else
{
boldedString = source;
}
return boldedString;
}
string phrase = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
string boldedPhrase = BoldBeforeString(phrase, "a", 41);
Hei!
I've tested this and it works:
String replaced = Regex.Replace(
"I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.",
#"(a) diplomatic",
match => "<strong>" + match.Result("$1") + "</strong>");
So to make it a general function:
public static String StrongReplace(String sentence, String toStrong, String wordAfterStrong)
{
return Regex.Replace(
sentence,
#"("+Regex.Escape(toStrong)+") " + Regex.Escape(wordAfterStrong),
match => "<strong>" + match.Result("$1") + "</strong>");
}
Usage:
String sentence = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
String replaced = StrongReplace(sentence, "a", "diplomatic");
edit:
considering your other comments, this is a function for placing strong tags around each word surrounding the search word:
public static String StrongReplace(String sentence, String word)
{
return Regex.Replace(
sentence,
#"(\w+) " + Regex.Escape(word) + #" (\w+)",
match => "<strong>" + match.Result("$1") + "</strong> " + word + " <strong>" + match.Result("$2") + "</strong>");
}
Related
Consider the following helper method
public static string ToSentenceCase(this string str)
{
return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1]));
}
Now when called as:
static void Main(string[] args)
{
string a = "HelloWorld";
Console.WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(a.ToSentenceCase()));
}
This will output Hello World which works great.
Using this method I'm trying to change the 3 first characters to uppercase if they start with the string RMA. Is there are way to achieve this using a regex or would I have to create another method and call it once I have my returned string from ToSentenceCase()?
So if I had a string rmainfo I would want RMA Info
You may use:
public static string ToSentenceCase(this string str)
{
var temp = Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1]));
return Regex.Replace(temp, "^rma.", m => m.Value.Substring(0, 3).ToUpper() + " " + char.ToUpper(m.Value[3]), RegexOptions.IgnoreCase);
}
If you insist on doing it with a regular expression, this could work:
var str = "rmaHelloWorld";
var str1 = Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1]));
var str2 = Regex.Replace(str1, "^rma", m => m.Value.ToUpper());
Console.WriteLine(str2);
I created a small function to catch a string between strings.
public static string[] _StringBetween(string sString, string sStart, string sEnd)
{
if (sStart == "" && sEnd == "")
{
return null;
}
string sPattern = sStart + "(.*?)" + sEnd;
MatchCollection rgx = Regex.Matches(sString, sPattern);
if (rgx.Count < 1)
{
return null;
}
string[] matches = new string[rgx.Count];
for (int i = 0; i < matches.Length; i++)
{
matches[i] = rgx[i].ToString();
//MessageBox.Show(matches[i]);
}
return matches;
}
However if i call my function like this: _StringBetween("[18][20][3][5][500][60]", "[", "]");
It will fail. A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd;
However i can not because i dont know if the character is going to be a bracket or a word.
Sorry if this is a stupid question but i couldn't find something similar searching.
A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; However i can not because i don't know if the character is going to be a bracket or a word.
You can escape all meta-characters by calling Regex.Escape:
string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);
This would cause the content of sStart and sEnd to be interpreted literally.
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’d like to create a method to replace delimiters for the intended target use (html email, log, database). The delimiters are constant so I’d like to be able to reference a object that maps recognizable names to string values (semicolon = “;”, htmlLineBreak = “<br/>”, etc.). Is there a better means to do this than this below?
public static class Utilities
{
public string ReplaceDelimiter(string content
, Delimiter currentDelimiter, Delimiter outputDelimiter)
{
return content.Replace(currentDelimiter.ToString()
, outputDelimiter.ToString());
}
}
public class Delimiter
{
public const string comma = ",";
public const string semicolon = ";";
public const string colon = ":";
public const string lineBreak = "\r\n";
public const string htmlLineBreak = "<br/>";
}
Edited following comments:
A use case would be when I want to log an error to different targets and send the same contents (formatted differently) in an email. The log may go to a database column (want key/value with semicolon delimiter) or log file (want delimiter to be line breaks). The email would be HTML so want the delimiter to be replaced with <br/>.
Below would be an excerpt from a logging method that has a few parameters including the actual Exception:
StringBuilder delimitedMessage = new StringBuilder();
delimitedMessage.Append("Date=" + DateTime.Now.ToShortDateString() + ";");
delimitedMessage.Append("Time=" + DateTime.Now.ToLongTimeString() + ";");
delimitedMessage.Append("Source=" + objException.Source.ToString().Trim() + ";");
delimitedMessage.Append("Method=" + objException.TargetSite.Name.ToString() + ";");
delimitedMessage.Append("Erring Method=" + methodName + ";");
delimitedMessage.Append("Computer=" + System.Environment.MachineName.ToString() + ";");
delimitedMessage.Append("Log Message=" + logMessage + ";");
delimitedMessage.Append("Exception Error=" + objException.Message.ToString().Trim() + ";");
delimitedMessage.Append("Severity=" + severity.ToString() + ";");
delimitedMessage.Append("Stack Trace=" + objException.StackTrace.ToString().Trim() + ";");
contentToLog = delimitedMessage.ToString();
WriteToDb(contentToLog);
WriteToLog(Utilities.ReplaceDelimiter(contentToLog, Delimiter.semicolon, Delimiter.lineBreak));
SendEmail(Utilities.ReplaceDelimiter(contentToLog, Delimiter.semicolon, Delimiter.htmlLineBreak));
Code
public class Delimiter {
public static readonly Delimiter
HtmlLineBreak=new Delimiter {
Value="<br/>"
},
LineBreak=new Delimiter {
Value="\r\n"
},
Semicolon=new Delimiter {
Value=";"
},
Colon=new Delimiter {
Value=":"
},
Comma=new Delimiter {
Value=","
};
public override String ToString() {
return Value;
}
public String Value {
get;
set;
}
}
Test
var t=Utilities.ReplaceDelimiter("123\r\n", Delimiter.LineBreak, Delimiter.HtmlLineBreak);
Debug.Print("{0}", t);
Output
123<br/>
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;
}
}