我有这个字符串:
Hello22, I'm 19 years old
如果数字前面有空格,我只想用*代替它,所以它看起来像这样:
Hello22, I'm ** years old
我已经尝试了很多正则表达式,但没有成功。希望有人能用正确的正则表达式帮上忙。非常感谢。
我尝试过的Regexes:
Regex.Replace(input, @"([d-])", "*");
返回所有替换为*的数字
Regex.Replace(input, @"(x20[d-])", "*");
无法按预期工作
您可以尝试(?<= )[0-9]+
模式,其中
(?<= ) - look behind for a space
[0-9]+ - one or more digits.
代码:
string source = "Hello22, I'm 19 years old";
string result = Regex.Replace(
source,
"(?<= )[0-9]+",
m => new string('*', m.Value.Length));
看看b[0-9]+b
(这里b
代表单词绑定(。此模式将替换"19, as I say, 19, I'm 19"
中的所有19
(注意,第一个19
之前没有空间(:
string source = "19, as I say, 19, I'm 19";
string result = Regex.Replace(
source,
@"b[0-9]+b",
m => new string('*', m.Value.Length));
在C#中,您还可以使用带有lookbacking和无限量词的模式。
(?<= [0-9]*)[0-9]
模式匹配:
(?<=
正向向后看,断言当前位置左边的是[0-9]*
匹配后面跟有可选数字0-9的空格
)
密切关注[0-9]
匹配个位数0-9
示例
string s = "Hello22, I'm 19 years old";
string result = Regex.Replace(s, "(?<= [0-9]*)[0-9]", "*");
Console.WriteLine(result);
输出
Hello22, I'm ** years old