Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C语言中,在两个字符之间拆分字符串#_C#_Asp.net_Regex_String_Split - Fatal编程技术网

C# 在C语言中,在两个字符之间拆分字符串#

C# 在C语言中,在两个字符之间拆分字符串#,c#,asp.net,regex,string,split,C#,Asp.net,Regex,String,Split,我有一个类型为“24;#usernamehere,#AWRFR\user,#,#,#usernamehere”的字符串 我想在#和,上第一次出现时分割此字符串,即我想提取介于这两个字符之间的字符串 因此,对于上面的字符串,我希望输出为: 用户名此处 如何使用Regex函数在两个字符之间拆分字符串?与您要求的方式不完全一样,但应该按照您的要求执行 string input = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere"; string use

我有一个类型为“24;#usernamehere,#AWRFR\user,#,#,#usernamehere”的字符串

我想在
#
上第一次出现时分割此字符串,即我想提取介于这两个字符之间的字符串

因此,对于上面的字符串,我希望输出为:

用户名此处


如何使用
Regex
函数在两个字符之间拆分字符串?

与您要求的方式不完全一样,但应该按照您的要求执行

string input = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string username = input.Substring(input.LastIndexOf("#") + 1);
如果你愿意,你可以得到第一和第二的位置

int hashPosition = input.IndexOf("#") + 1;
int commaPosition = input.IndexOf(",");

string username = input.Substring(hashPosition, commaPosition - hashPosition));

您需要找到“#”和“,”的第一个索引。然后使用substring方法获得所需的修剪字符串。有关子字符串方法的详细信息,请阅读

string s = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string finalString = s.Substring(s.IndexOf('#') + 1, s.IndexOf(',') - s.IndexOf('#') - 1);
使用Linq:

using System.Linq;
var input = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
您可以用一行将其拆分:

var x = input.Split('#').Where(e => e.Contains(',')).Select(e => e.Split(',').First());
这与:

var x = from e in input.Split('#') 
        where e.Contains(',') 
        select e.Split(',').First();
在这两种情况下,结果都是:

x = {"usernamehere", "AWRFR\user", "", ""}
这正是一个数组,所有子字符串都由
包围。 然后,如果需要第一个元素,只需添加
.first()
或执行以下操作:

x.First();

一个简单的正则表达式模式可以完成这项工作:

var pattern = new System.Text.RegularExpressions.Regex("#(?<name>.+?),");

听起来像是正则表达式的工作…您尝试过方法
String.Split()
-
string s = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
pattern.Match(s).Groups["name"].Value;   //usernamehere