【问题标题】:How to get the last and first special chars of a string?如何获取字符串的最后一个和第一个特殊字符?
【发布时间】:2016-11-11 09:58:44
【问题描述】:

我在一个列表中有几个字符串:

List<string> mylist = new List<string>();
mylist.Add("_+hello[]_");
mylist.Add("_+how||");
mylist.Add("_+are,,");
mylist.Add("||you=_");
mylist.Add("_+doing\"_");

我想将最后一个和第一个特殊字符 (+,_[]=") 全部放入数组中。

string[,] array = new string[5,2]

我的数组最后应该看起来像这样:

_+ AND [] _
_+ AND ||
_+ AND ,,
|| AND =_
_+ AND "_

有人知道怎么做吗?

提前致谢

【问题讨论】:

  • 到目前为止你想出了什么?
  • 这没有意义,你想要第一个字符但想要返回_+
  • 试试Regex.Split(str, @"[^\W_]+")
  • @WiktorStribiżew 请将此作为答案发布,这太棒了
  • 发布了两个正则表达式的变体。

标签: c# arrays regex split


【解决方案1】:

您似乎想用字母数字字符分割。由于\w 匹配字母数字或下划线字符,您可以将subtract 和_ 组合起来并与Regex.Split 一起使用:

Regex.Split(str, @"[\w-[_]]+")

见this regex demo

或者

Regex.Split(str, @"[^\W_]+")

这是regex demo

[^\W_] 匹配任何不是非单词字符的字符(即,它匹配任何\w)而不是_(因此,除了_ 之外的任何_,否则会得到匹配)。

【讨论】:

  • 谢谢,这正是我想要的
  • 只是不要尝试"+hello there+"
  • @C.Evenhuis:OP 输入不包含空格。这种情况的要求是必要的。为了避免得到空白块,模式可以是[\w\s-[_]]+
  • @WiktorStribiżew 我同意这是未定义的,但我敢打赌他不想要只这些确切的输入值,否则他可以硬编码结果。 OP 已经接受了你的回答,这只是他可能想知道的。
【解决方案2】:
    List<string> mylist = new List<string>();
    mylist.Add("_+hello[]_");
    mylist.Add("_+how||");
    mylist.Add("_+are,,");
    mylist.Add("||you=_");
    mylist.Add("_+doing\"_");
    foreach (var item in mylist)
    {
        var LastItem=item.ToArray().Last();
        var FirstItem = item.ToArray().First();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2020-11-19
    • 2019-09-10
    • 2021-02-11
    • 2011-07-07
    • 2011-08-17
    相关资源
    最近更新 更多