【问题标题】:Split A String On Certain Condition在特定条件下拆分字符串
【发布时间】:2019-09-04 19:51:17
【问题描述】:

我有一个要求,我必须拆分具有以下格式的字符串:

1234-5678-91011_ABCD_EFGH

所以我使用下面的代码使它工作并且完成了:

string str = "1234-5678-91011_ABCD_EFGH";
String[] parts = str.Split("_"); //Spliting The String Here
string part1 = "";
string part2 = "";
string part3 = "";

if (parts.Length > 2 && parts[2] != null)
{
   part1 = parts[0]; //Retrieves The First Part
   part2 = parts[1]; //Second Part
   part3 = parts[2]; //Third Part
}

所以最终输出是这样的:1234-5678-91011 ABCD EFGH 我需要在其中获取带有破折号的第一部分。所以很基本。现在的要求是:1234-5678-91011-ABCD-EFGH,我必须再次检索它 - 1234-5678-91011。这部分可以是任何东西,数字或单词。有什么方法可以用新格式检索第一部分?

注意:基本上,这个东西来自 1234-5678-91011_ABCD_EFGH 来自与模型属性连接的锚点。所以默认情况下, 是这样的:

1234 5678 91011
ABCD
EFGH

<a href="./@(item.Part1.Replace(" ", "-") + "_" + item.Part2 + "_" + item.Part3)">@item.Part1 @item.Part2 @item.Part3</a>

单击该链接会将我重定向到另一个页面,我需要在该页面中获取第一部分或第一部分的值。

【问题讨论】:

  • 您可以在客户端设置任何数据格式。为什么它应该是完全手动创建的字符串而不是 json 字符串格式?在这种情况下,您不应按条件拆分字符串。
  • 这是否是精确的 13 位数字或字符,由 - 分隔的 4、4 和 5 组?

标签: c# asp.net-core split


【解决方案1】:

你可以在正则表达式的帮助下尝试匹配;如果

这部分可以是任何东西,数字或单词

表示我们可以使用\w 的任何单词符号,如果它可以是任意符号-,那么[^-] 可以

 using System.Text.RegularExpressions;

 ...

 string source = "1234-5678-91011-ABCD-EFGH";

 // 1234-5678-91011
 string result = Regex.Match(source, @"\w+-\w+-\w+").Value;

您可能希望为零件设置单独的组:

 var match = Regex.Match(source, @"(\w+)-(\w+)-(\w+)");

 if (match.Success) {
    string part1 = match.Groups[1].Value; // "1234"
    string part2 = match.Groups[2].Value; // "5678"
    string part3 = match.Groups[3].Value; // "91011" 

    string all = match.Value;             // "1234-5678-91011"

    ... 
 }

最后,如果字符串必须从数字开始,则在模式中添加^@"^(\w+)-(\w+)-(\w+)"

【讨论】:

  • 请注意,“这部分可以是任何东西,数字或单词”——这是指前三个部分,所以[0-9]+ 不适用。
  • @Michał Turczyn:谢谢!我懂了;所以它可以是\w如果“任何东西、数字或单词”表示任何单词符号或[^-]如果它表示任意字符但-
  • 正确 :) 任何不包含 - 的字符类 [...]+ 都是很好的解决方案 :) 但我会选择更严格的 [a-z0-9]i 标志,这意味着不区分大小写:)
【解决方案2】:

然后连接三个第一个条目:

string[] parts = str.Split("-");
string part1 = "";
string part2 = "";
string part3 = "";

if(parts.Length > 4)
{
  part1 = $"{parts[0]}-{parts[1]}-{parts[2]}";
  part2 = parts[3];
  part2 = parts[4];
}
else if (parts.Length > 2)
{
  part1 = parts[0]; //Retrieves The First Part
  part2 = parts[1]; //Second Part
  part3 = parts[2]; //Third Part
}

用破折号分割收到的字符串后。

【讨论】:

    猜你喜欢
    • 2018-12-02
    • 2021-03-05
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多