从字符串中提取未指定的字符

时间:2018-09-04 08:55:17

标签: c# string

我试图弄清楚如何从字符串中提取未指定的字符。

例如:我有长字符串"1.1.1 sadsajkdn 1.1.2.1 dfkjskf 2.1.1",依此类推。我想做的是在每个数字后分割字符串。我已经按照先前的教程使用string.split('1'),但是我需要提取可能不同的整数部分。我可以指定诸如string.split('*.*.*')之类的东西,其中的star代表1-9之间的任何数字吗?

谢谢

1 个答案:

答案 0 :(得分:3)

我建议使用regular expressions。我相信你想要

  • 至少一位数字
  • 尽可能多地出现“点后至少一位数字”

的正则表达式表示
<xsl:template match="//a">
    <xsl:copy>
        <xsl:apply-templates select="./*[not(local-name()='b') and not(local-name()='c')]"/>
    </xsl:copy>
    <xsl:apply-templates select="./b"/>
    <xsl:apply-templates select="./c"/>
</xsl:template>
  • \d+(\.\d+)* 的意思是“数字”
  • \d的意思是“至少一个”
  • +的意思是“点”(仅\.的意思是“任何字符”)
  • .的意思是“零个或多个”
  • 括弧式将“点号后跟至少一位数字”分组

下面是一个完整的示例,展示了这一点:

*

(提取所有值的方法可能更简单。您可以调用using System; using System.Collections.Generic; using System.Text.RegularExpressions; class Test { static void Main() { List<string> pieces = SplitToDottedNumbers("1.1.1 sadsajkdn 1.1.2.1 dfkjskf 2.1.1"); foreach (string piece in pieces) { Console.WriteLine(piece); } } static List<string> SplitToDottedNumbers(string text) { // Inline for readability. You could create this just once. var regex = new Regex(@"\d+(\.\d+)*"); // LINQ-based implementation return regex.Matches(text) .Cast<Match>() .Select(match => match.Value) .ToList(); /* Alternative implementation var pieces = new List<string>(); var match = regex.Match(text); while (match.Success) { pieces.Add(match.Value); match = match.NextMatch(); } return pieces; */ } }

相关问题