【问题标题】:Split after some value在某个值后拆分
【发布时间】:2017-06-30 15:20:46
【问题描述】:

我有这个输入:

标题 #14 第一个 324.36 美元 第二个 GUY 261 美元 第三个 33 101 美元

我想拆分该字符串以保存在数据库中。

所以The title #14 是一个标题,它可能是 1 个单词或多个单词,但它们都有 # 和一些 int 值(也可能是 #2222

在该标题之后,我想获得first324.36Second-GUY261 等。我该怎么做?

我知道拆分,所以我可以input.Split('#'),但我不知道如何处理该 int。

在第二方面,我将与USD分开

我想成为的第一个值:The Title #14

秒:first 324.36

第三个:Second-GUY 261

如图所示:

【问题讨论】:

  • 你也应该考虑正则表达式
  • @maccettura 你能告诉我怎么做吗?现在我没有使用正则表达式的经验
  • 对正则表达式的要求不明确。
  • @WiktorStribiżew:你可以从那句话中删除for a regex
  • @gsiradze 所以他们不会都,对于标题,最后一个值是 #123 所以你可以分割空间并阅读标题。作为开始,您可以阅读以 # 开头的字段,然后您就有了标题。然后你就可以知道之后的每个字段是什么,除非其他字段也有空格。

标签: c# regex string split


【解决方案1】:

这可能有助于解决问题

string lsInput = "The Title #14 first 324.36 USD Second-GUY 261 USD Third33 101 USD";
var loMatch = Regex.Match(lsInput, @"(?<title>.*#\d+)\s(?<parts>.*)");
string lsTitle = loMatch.Groups["title"].Value; //The Title #14
var loParts = loMatch.Groups["parts"].Value.Split(new string[] { "USD" },  StringSplitOptions.RemoveEmptyEntries).
   Select(item => item.Trim()).ToList();

输出loParts:

Count = 3
[0]: "first 324.36"
[1]: "Second-GUY 261"
[2]: "Third33 101"

【讨论】:

  • 在“USD”上拆分 loParts,这是最好的解决方案。
  • 做了一个fiddle 显示美元的分割
  • @maccettura 是的,如果按美元拆分,那么你就有了输出。
【解决方案2】:

Regex Class 非常适合这样的任务,编写一个模式并让Regex 类来完成这项工作。
这是一个示例,展示如何根据您的字符串使用正则表达式。
请阅读示例中的我的 cmets:

private void button1_Click(object sender, EventArgs e)
{
    string Target = "The Title #14 first 324.36 USD Second-GUY 261 USD Third33 101 USD";
    var value = string.Empty;
    var pattern = "(The Title) ([#]{1})([0-9]{1,500})";

    if (Example(Target,pattern, ref value) == true) 
    {
        MessageBox.Show(value); // output: The Title #14
    }

    pattern = "(first) ([0-9]{1,500}(.)[0-9]{1,500})";

    if (Example(Target, pattern, ref value) == true) 
    {
        MessageBox.Show(value); // output: first 324.36, if you want only the number one way is to replace  MessageBox.Show(value); to MessageBox.Show(value.Replace("first",""));
    }

    pattern = "(Second-GUY) ([0-9]{1,500}(.)[0-9]{1,500})";

    if (Example(Target, pattern, ref value) == true) 
    {
        MessageBox.Show(value); // output: Second-GUY 261, if you want only the number one way is to replace  MessageBox.Show(value); to MessageBox.Show(value.Replace("Second-GUY",""));
    }
}

private bool Example(string Target,string pattern, ref string value)
{

    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);
    bool ismatched = reg.IsMatch(Target);

    if (ismatched)
    {
        System.Text.RegularExpressions.Match match = reg.Match(Target);
        value = match.Value;
    }

    return ismatched;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多