簡體   English   中英

如何在字符串中使用空格將數字與單詞,字符和任何其他標記分開

[英]How to separate numbers from words, chars and any other marks with whitespace in string

我正在嘗試將數字與單詞或字符以及字符串中帶有空格的任何其他標點符號分開寫入它們,例如,字符串為:

 string input = "ok, here is369 and777, and 20k0 10+1.any word.";

所需的輸出應為:

 ok, here is 369 and 777 , and 20 k 0 10 + 1 .any word. 

我不確定我的方法是否正確,但是現在我要嘗試的是查找字符串是否包含數字,然后以某種方式將其全部替換為相同的值,但之間使用空格。 如果有可能,我如何找到所有單獨的數字(不是每個數字都更清晰),用單詞或空格分隔或不分隔,並將每個找到的數字附加到值上,這些值可一次全部用於替換具有相同的數字,但側面帶有空格。 這樣,它僅返回字符串中數字的首次出現:

class Program
{
    static void Main(string[] args)
    {
        string input = "here is 369 and 777 and 15 2080 and 579"; 
        string resultString = Regex.Match(input, @"\d+").Value;

        Console.WriteLine(resultString);

        Console.ReadLine();
    }
}

輸出:

369

但是我也不確定是否可以為每個替換值獲得所有不同的發現編號。 最好找出去向

如果我們基本上需要在數字周圍添加空格,請嘗試以下操作:

string tmp = Regex.Replace(input, @"(?<a>[0-9])(?<b>[^0-9\s])", @"${a} ${b}");
string res = Regex.Replace(tmp,   @"(?<a>[^0-9\s])(?<b>[0-9])", @"${a} ${b}");

先前的答案假定單詞,數字和標點符號應分開:

string input = "here is369 and777, and 20k0";
var matches = Regex.Matches(input, @"([A-Za-z]+|[0-9]+|\p{P})");
foreach (Match match in matches)
    Console.WriteLine("{0}", match.Groups[1].Value);

簡短地構造所需的結果字符串:

string res = string.Join(" ", matches.Cast<Match>().Select(m => m.Groups[1].Value));

您走在正確的道路上。 Regex.Match僅返回一個匹配項,您必須使用.NextMatch()來獲取與您的正則表達式匹配的下一個值。 Regex.Matches將所有可能的匹配Regex.Matches返回到MatchCollection ,然后可以像我在示例中所做的那樣,使用循環解析該匹配:

string input = "here is 369 and 777 and 15 2080 and 579";

        foreach (Match match in Regex.Matches(input, @"\d+"))
        {
            Console.WriteLine(match.Value);
        }

        Console.ReadLine();

輸出:

369
777
15
2080
579

這提供了所需的輸出:

string input = "ok, here is369 and777, and 20k0 10+1.any word.";
var matches = Regex.Matches(input, @"([\D]+|[0-9]+)");
foreach (Match match in matches)
    Console.Write("{0} ", match.Groups[0].Value);

[\\ D]將匹配非數字的任何內容。 請注意{0}后的空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM