在c#中使用任意字符在某些点查找字符串中的字符串
本文关键字:字符串 查找 字符 任意 | 更新日期: 2023-09-27 18:11:11
我想不出最好的方式来解释这一点,但是如何去做像text.Replace("1*6", "hello")
这样的事情呢?
其中 *
表示字符/数字,可以是任何东西,因此"116"
, "126"
, "1e6"
等都将被以相同的方式处理并被替换为"hello"
。
这将为您工作:
var text = "This is 1x6 in a string.";
var result = Regex.Replace(text, "1.6", "hello");
这给我的结果是:
这是字符串形式的hello。
使用正则表达式:
string input = "126";
string output = Regex.Replace(input, "1.6", "hello");
关于正则表达式的更多信息:http://msdn.microsoft.com/en-us/library/xwewhkd1 (v = vs.110) . aspx
使用regex代替
static class Program
{
/// <summary>
/// Regular expression built for C# on: Thu, Jul 3, 2014, 02:47:43 PM
/// Using Expresso Version: 3.0.4750, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// 1.6
/// 1
/// Any character
/// 6
///
///
/// </summary>
public static Regex regex = new Regex(
"1.6",
RegexOptions.CultureInvariant
| RegexOptions.Compiled
);
// This is the replacement string
public static string regexReplace =
"hello";
static void Main(string[] args)
{
string input = @"
116,
1e6
";
string result = regex.Replace(input, regexReplace);
Console.WriteLine(result);
}
}