gpt4 book ai didi

c# - 在 C# 中提取仅包含字母的字符串

转载 作者:行者123 更新时间:2023-12-01 22:26:28 25 4
gpt4 key购买 nike

 string input = "5991 Duncan Road";
var onlyLetters = new String(input.Where(Char.IsLetter).ToArray());

输出:DuncanRoad

但我期望输出是 Duncan Road。需要改变什么?

最佳答案

对于像您这样的输入,您不需要正则表达式,只需跳过所有以 SkipWhile() 开头的非字母符号即可:

Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.

C#代码:

var input = "5991 Duncan Road";
var onlyLetters = new String(input.SkipWhile(p => !Char.IsLetter(p)).ToArray());
Console.WriteLine(onlyLetters);

参见 IDEONE demo

一个 regx 解决方案,将删除不属于单词的数字以及相邻的空格:

var res = Regex.Replace(str, @"\s+(?<!\p{L})\d+(?!\p{L})|(?<!\p{L})\d+(?!\p{L})\s+", string.Empty); 

关于c# - 在 C# 中提取仅包含字母的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33753573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com