[英]Replace values in string
我正在寻找在字符串中找到匹配项,对该匹配项执行操作,然后替换原始匹配项。
例如,在字符串中找到@yahoo,寻找将与号后面的所有内容都匹配到第一个空格。 当然,在单个字符串中可以有多个匹配的值,因此每个匹配都将有一个。
我正在考虑使用正则表达式,但是不确定是否将与号后面的所有内容都匹配到第一个空格(为此使用正则表达式吗?)。 或任何其他更简单的方式做到这一点?
假设您正确设置了Regex,则可以利用Regex.Replace的重载之一来包含MatchEvaluator委托。 MatchEvaluator
是Func<Match,string>
委托(意味着任何public string Method(Match match)
方法都将用作输入),返回值是您想要替换原始字符串的值。 搜索的正则表达式为(@\\S+)
,表示“匹配@
符号,后接任何非空白字符( \\S
)至少一次( +
)。
Regex.Replace(input, "(@\S+)", (match) => { /* Replace logic here. */ })
@yahoo.com is going to be @simple for purposes of @matching.
在输入@yahoo.com is going to be @simple for purposes of @matching.
上运行上述正则表达式@yahoo.com is going to be @simple for purposes of @matching.
,它与@yahoo.com
, @yahoo.com
@simple
和@matching.
(请注意,它包括@matching上的@matching.
)。
希望有帮助!
如果您使用C#编写,则正则表达式可能是您的最佳选择。 代码很简单
MatchCollection matches = Regex.Matches(/*input*/, /*pattern*/)
foreach (Match m in matches)
{
/*Do work here*/
}
为了学习正则表达式和相关的语法,我使用http://www.regular-expressions.info/tutorial.html入门。 那里有很多很好的信息,而且易于阅读。
例如:
string str = "@yahoo aaaa bbb";
string replacedStr = str.Replace("@yahoo", "replacement");
查看文档: string.Replace
你的意思是符号&
或符号@
?
这应该可以满足您的需求: &([\\S\\.]+)\\b
或符号符号: @([\\S\\.]+)\\b
尝试使用String.Replace()函数:
String x="lalala i like being @Yahoo , my Email is John@Yahoo.com";
x=x.Replace("@Yahoo","@Gmail");
X现在是:“拉拉拉,我喜欢当@Gmail,我的电子邮件是John@Gmail.com”;
要知道“ @Yahoo”之后的下一个空格,请使用具有String.IndexOf()和String.LastIndexOf()的位置变量。
int location=x.IndexOf("@Yahoo");//gets the location of the first "@Yahoo" of the string.
int SpaceLoc=x.IndexOf("@Yahoo",location);// gets the location of the first white space after the first "@Yahoo" of the string.
希望能有所帮助。
我认为RegEx.Replace是您最好的选择。 您可以简单地执行以下操作:
string input = "name@yahoo.com is my email address";
string output = Regex.Replace(input, @"@\S+", new MatchEvaluator(evaluateMatch));
而且,您只需要定义validateMatch方法,例如:
private string evaluateMatch(Match m)
{
switch(m.Value)
{
case "@yahoo.com":
return "@google.com";
break;
default:
return "@other.com";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.