当谈到正则表达式时,我是一个完整的新手,并且想知道是否有人可以帮助我。我不确定在这里使用regEx是否正确,所以如果你有更好的想法,请随意加入。 (我将通过许多字符串循环)。
基本上,我想在字符串上查找/替换,用{}包装匹配并保留字符串的原始大小写。
示例:
Source: "The CAT sat on the mat."
Find/Replace: "cat"
Result: "The {CAT} sat on the mat."
我希望find / replace仅适用于第一次出现,我还需要知道find / replace是否确实匹配。
我希望我已经清楚地解释了事情。
谢谢。
答案 0 :(得分:5)
Regex theRegex =
new Regex("(" + Regex.Escape(FindReplace) + ")", RegexOptions.IgnoreCase);
theRegex.Replace(Source, "{$1}", 1);
如果您想要字边界容差:
Regex theRegex =
(@"([\W_])(" + Regex.Escape(FindReplace) + @")([\W_])", RegexOptions.IgnoreCase)
theRegex.Replace(str, "$1{$2}$3", 1)
答案 1 :(得分:1)
如果你要循环遍历许多字符串,那么也许Regex可能不是最好的主意 - 它是一个很棒的工具,但不是最快的。
以下是一个可行的示例代码:
var str = "The Cat ate a mouse";
var search = "cat";
var index = str.IndexOf(search, StringComparison.CurrentCultureIgnoreCase);
if (index == -1)
throw new Exception("String not found"); //or do something else in this case here
var newStr = str.Substring(0, index) + "{" + str.Substring(index, search.Length) + "}" + str.Substring(index + search.Length);
修改强>
如评论中所述,上述代码存在一些问题。
因此,我决定尝试找到一种方法,使其无需使用正则表达式。不要误会我的意思,我和下一个人一样喜欢正则表达式。我这样做主要是出于好奇。 ;)
这就是我发现的:
public static class StringExtendsionsMethods
{
public static int IndexOfUsingBoundary(this String s, String word)
{
var firstLetter = word[0].ToString();
StringBuilder sb = new StringBuilder();
bool previousWasLetterOrDigit = false;
int i = 0;
while (i < s.Length - word.Length + 1)
{
bool wordFound = false;
char c = s[i];
if (c.ToString().Equals(firstLetter, StringComparison.CurrentCultureIgnoreCase))
if (!previousWasLetterOrDigit)
if (s.Substring(i, word.Length).Equals(word, StringComparison.CurrentCultureIgnoreCase))
{
wordFound = true;
bool wholeWordFound = true;
if (s.Length > i + word.Length)
{
if (Char.IsLetterOrDigit(s[i + word.Length]))
wholeWordFound = false;
}
if (wholeWordFound)
return i;
sb.Append(word);
i += word.Length;
}
if (!wordFound)
{
previousWasLetterOrDigit = Char.IsLetterOrDigit(c);
sb.Append(c);
i++;
}
}
return -1;
}
}
但我不能相信这一点!我在谷歌搜索here, on StackOverflow之后找到了这个,然后对其进行了修改。 ;)
使用此方法代替上述代码中的标准IndexOf
。
答案 2 :(得分:1)
试试这个:
class Program
{
const string FindReplace = "cat";
static void Main(string[] args)
{
var input = "The CAT sat on the mat as a cat.";
var result = Regex
.Replace(
input,
"(?<=.*)" + FindReplace + "(?=.*)",
m =>
{
return "{" + m.Value.ToUpper() + "}";
},
RegexOptions.IgnoreCase);
Console.WriteLine(result);
}
}