问题
我有两个字符串s1和s2
string s1 = " characters of a string, creating a new string object. An array U.A.E of characters is passed to this method to U.A.E specify U.A.E the characters to be removed. The order of the elements in the character array does not affect the trim operation.";
string s2 = " An array UAE of characters is passed to this method to UAE specify UAE " ;
我在标签中显示字符串s1。并希望在s1中加粗s2部分。
即label1.Text = " characters of a string, creating a new string object. <b> An array U.A.E of characters is passed to this method to U.A.E specify U.A.E </b> the characters to be removed. The order of the elements in the character array does not affect the trim operation.";
我可以将<b>
放在s2的开头和</b>
结尾处。但是在s1的U.A.E中有点(&#39;。&#39;)但在s2中有阿联酋。
我尝试了什么。
我试图获得第一个索引和最后一个要替换的单词索引。
int x = s1.Replace(".", "").IndexOf(s2);
但是,随着阿联酋的重复,未能获得最后一个指数。
我试图将<b> </b>
分别放在s2中的所有单词中。但这些话可能会在s1中重复。
我想知道是否有任何字符串函数,通过它我可以用不需要的点替换s1的s2部分
注意:阿联酋只是一个例子,点可能有任何单词
答案 0 :(得分:5)
对于可能包含或不包含其他.
个字符的所有字符串的一般解决方案,您需要根据第二个字符串动态构建正则表达式:
var s1 = "Here is a U.A.E string";
var s2 = "UAE string";
//Find all the characters that need an optional . after them
var r = new Regex(@"(\S)(?=\S)");
//Perform a replace on s2 to create a new regex with optional dots, surrounded by () so we capture it
var r2 = new Regex("(" + r.Replace(s2, @"$1\.?") + ")");
//r2 is now a regex containing "(U\.?A\.?E s\.?t\.?r\.?i\.?n\.?g)"
//Use that regex to perform the actual replace, using the captured group to reinsert
var replacedString = r2.Replace(s1, "<b>$1</b>");
//replacedString contains "Here is a <b>U.A.E string</b>"
答案 1 :(得分:3)
string s1 = " characters of a string, creating a new string object. An array U.A.E of characters is passed to this method to U.A.E specify U.A.E the characters to be removed. The order of the elements in the character array does not affect the trim operation.";
string s2 = " An array UAE of characters is passed to this method to UAE specify UAE ";
// regex will ignore any dot in tested string while searching pattern
var regex = new Regex(String.Join(@"\.*", s2.AsEnumerable()));
var result = regex.Replace(s1, m => "<b>" + m.ToString() + "<b>");
答案 2 :(得分:0)
你可以试试这样的事情
string s1 = " characters of a string, creating a new string object. An array U.A.E of characters is passed to this method to U.A.E specify U.A.E the characters to be removed. The order of the elements in the character array does not affect the trim operation.";
string s2 = " An array UAE of characters is passed to this method to UAE specify UAE ";
s1 = s1.Replace("U.A.E", "UAE");
s1 = s1.Replace(s2, "<b>"+s2+"</b>");
答案 3 :(得分:0)
如果您想要替换&#34; UAE&#34;,在字符之间有或没有点,您可以使用
s1 = Regex.Replace(s1, @"(U\.?A\.?E\.?)", "<b>$1</b>");
\.
搜索文字.
(没有\
它会匹配任何字符)。 ?
表示该点是可选的。
括号用于对匹配的子字符串进行分组,以便替换字符串中的$1
可以插入。{/ p>