我在C#中有一个带有“wiki语法”的字符串,我想替换它中的值。
"My '''random''' text with '''bold''' words."
translate to:
"My <b>random</b> text with <b>bold</b> words."
问题在于我想将值对替换为不同的值。
odd ''' => <b>
even ''' => </b>
答案 0 :(得分:2)
再添加一个选项:Regex.Replace可以与指定替换字符串的回调一起使用:
var txt = "My '''random''' text with '''bold''' words.";
int i = 0;
var newtext = new Regex("'''").Replace(txt, m => i++ % 2 == 0 ? "<B>" : "</B>" );
答案 1 :(得分:0)
邪恶黑客:包含空格和
replace " '''" with <b>
and "''' " with </b>
直到因某种原因失败为止;)
答案 2 :(得分:0)
这也应该有效:
static string ReplaceEvenOdd(string s, string syntax, string odd, string even)
{
string[] split = s.Split(new[] { syntax }, StringSplitOptions.None);
string result = string.Empty;
for (int i = 0; i < split.Length; i++)
{
result += split[i];
if (i < split.Length - 1)
result += (i + 1) % 2 == 0 ? even : odd;
}
return result;
}
答案 3 :(得分:0)
你可以这样做。
string c = "My '''random''' text with '''bold''' words.";
string[] tags = {"<b>", "</b>"};
for (int i = 0, index; (index = c.IndexOf("'''", StringComparison.Ordinal)) > 0; i++)
{
var temp = c.Remove(index, 3);
c = temp.Insert(index, tags[i % 2]);
}
'''
IndexOf
将返回否定数字其他明智的将给出'''
的位置'''
)。<b>
,则</b>
答案 4 :(得分:0)
虽然这有一个类似于其他答案的循环,但是一个微小的区别是选择开始和结束标签 - 而不是计算模2以确定我们是否使用开始或结束标签,我在一个标签中定义大小为2的数组:
String[] replaceText = new String[] { "<B>", "</B>" };
根据变量iReplacerIndex
replaceText[iReplacerIndex] // Gives either the opening or closing tag
通过从1减去所需值之间的切换。
iReplacerIndex = 1 - iReplacerIndex; // If last used was an opening tag,
// then next required is a closing tag
以上也可以轻松检查不匹配的标签 - 如果循环后iReplacerIndex
不为0,则标签不匹配。
整个代码如下(为了清晰起见,它的长度超过了它):
String sourceText = "My '''random''' text with '''bold''' words.";
int sourceLength = sourceText.Length;
String searchText = "'''";
int searchLength = searchText.Length;
String[] replaceText = new String[] { "<B>", "</B>" };
int iReplacerIndex = 0
, iStartIndex = 0
, iStopIndex = sourceText.Length - 1;
System.Text.StringBuilder sbCache = new System.Text.StringBuilder(sourceText.Length * 2);
do
{
iStopIndex = sourceText.IndexOf(searchText, iStartIndex);
if (iStopIndex == -1)
{
sbCache.Append(sourceText.Substring(iStartIndex, sourceLength - iStartIndex));
}
else
{
sbCache.Append(sourceText.Substring(iStartIndex, iStopIndex - iStartIndex));
sbCache.Append(replaceText[iReplacerIndex]);
iReplacerIndex = 1 - iReplacerIndex;
iStartIndex = iStopIndex + searchLength;
}
} while (iStopIndex != -1);
Console.WriteLine(sbCache.ToString());