使用C#正则表达式将span字符替换为span标记. [英] Replace speacial characters with span tag using c# regular expressions.
问题描述
我们有一个测试,例如这是一个错误(正在解决)?& @#17066.".
用以下逻辑修改测试后:
We have a test like "This is a bug (solveing) ? & @ # 17066.".
After we modify the test with below logic :
// replace <br /> tags with new line characters
string replaceContent = Regex.Replace(contentText, @"", "\n");
// add full stop to inner text of an element, if it needs one, to separate from next word when tags removed
replaceContent = Regex.Replace(replaceContent, @"\w(?=)", @"$0\.");
// remove all tags and leading and trailing space
replaceContent = Regex.Replace(replaceContent, "<.*?>", string.Empty).Trim();
CommonMethods.WordMatchCollection = CommonMethods.WordRegularExpression.Matches(replaceContent);
// match words which are not in tags
string pattern = @"(?<!<[^>]*?)\b(\w+|\w+['-]\w+)\b(?![^<]*?>)";
string replacement = "<span>$0</span>";
// surround words in text with <span> tags
contentText = Regex.Replace(contentText, pattern, replacement);
return contentText;</span>
格式化的测试如下:-
这 是 a bug (正在解决) ? & amp ; @# 17066 .
我们还要为#,$,@等特殊字符添加Span标签.
我们该怎么做.
The formated test is as follows:-
This is a bug (solveing) ? & @ # 17066.
We want to add Span tags for Speacial character like #, $, @ etc also.
How we can do this.
Thanks in Advanced.
推荐答案
0 \."); // 删除所有标签以及前后空格 replaceContent = Regex.Replace(replaceContent," ,字符串 .Empty).Trim(); CommonMethods.WordMatchCollection = CommonMethods.WordRegularExpression.Matches(replaceContent); // 匹配不在标签中的单词 字符串 pattern = @" ; 字符串替换= "
0\."); // remove all tags and leading and trailing space replaceContent = Regex.Replace(replaceContent, "<.*?>", string.Empty).Trim(); CommonMethods.WordMatchCollection = CommonMethods.WordRegularExpression.Matches(replaceContent); // match words which are not in tags string pattern = @"(?<!<[^>]*?)\b(\w+|\w+['-]\w+)\b(?![^<]*?>)"; string replacement = "<span>
0</span>"; // 用< span>包围文本中的单词标签 contentText = Regex.Replace(contentText,pattern,replacement); 返回 contentText; </ span >
0</span>"; // surround words in text with <span> tags contentText = Regex.Replace(contentText, pattern, replacement); return contentText;</span>
格式化的测试如下:-
这 是 a bug (正在解决) ? & amp ; @# 17066 .
我们要为#这样的特殊字符添加Span标签,
The formated test is as follows:-
This is a bug (solveing) ? & @ # 17066.
We want to add Span tags for Speacial character like #,
,@等.
我们该怎么做.
感谢进阶.
, @ etc also.
How we can do this.
Thanks in Advanced.
这篇关于使用C#正则表达式将span字符替换为span标记.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!