gpt4 book ai didi

c# - 如何使用 C# 从字符串中提取子字符串?

转载 作者:太空狗 更新时间:2023-10-29 20:42:45 25 4
gpt4 key购买 nike

字符串格式总是这样“FirstName=ABC;LastName=XZY;Username=User1;Password=1234”。

我需要唯一的 UserName 值(在本例中为“User1”)。我想使用子字符串方法(或其他方法)以最少的代码行实现这一点。

帮忙吗?

最佳答案

为了完整起见,这里是正则表达式的实现方式。如果订单发生变化,这也将起作用。

// using System.Text.RegularExpressions;

string test1 = "FirstName=ABC;LastName=XZY;Username=User1;Password=1234";
string test2 = "FirstName=ABC;LastName=XZY;Password=1234;Username=User1";
string test3 = "FirstName=ABC;LastName=XZY;Password=1234";

string regexPattern = @"(?<=Username=)[^;\n]*";
var userName1 = Regex.Match(test1, regexPattern).Value; // User1
var userName2 = Regex.Match(test2, regexPattern).Value; // User1
var userName3 = Regex.Match(test3, regexPattern).Value; // string.Empty

// Compiling can speed up the Regex, at the expense of longer initial Initialization
// Use when this is called often, but measure.

Regex compiledRx = new Regex(regexPattern,RegexOptions.Compiled);
var userNameCompiled1 = compiledRx.Match(test1).Value; // User1
var userNameCompiled2 = compiledRx.Match(test2).Value; // User1
var userNameCompiled3 = compiledRx.Match(test3).Value; // string.Empty

关于c# - 如何使用 C# 从字符串中提取子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2313326/

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