【问题标题】:Split the string using array of delimiters in r使用 r 中的分隔符数组拆分字符串
【发布时间】:2015-04-22 05:39:57
【问题描述】:

我是 R 新手。我必须根据短语分隔符拆分句子。我们可以使用 strsplit 根据一个分隔符拆分字符串。我想根据分隔符的数量分割字符串,例如 [, . : ; ]。我怎样才能一步到位。有没有适用于此的正则表达式?

例如:

my_string = "This is a sentence.  This is a question, right?  Yes!  It is."

预期输出:

"This is a sentence", "This is a question", "right", "yes", "It is"

【问题讨论】:

  • 你能分享一些示例字符串和预期的输出吗?
  • 你能给我们看一些例子和代码吗?
  • 使用内置字符集可能会有所帮助:strsplit(my_string, "[[:punct:]](\\s+|$)"),尽管不可否认,这并不适用于所有上下文。

标签: regex r


【解决方案1】:

你可以用这个:

strsplit("This is a sentence. This is a question, right? Yes! It is.", "\\.|,|\\?|!")
#[[1]]
#[1] "This is a sentence"  " This is a question" " right"             
#[4] " Yes"                " It is"

要去掉那些多余的空格,你可以这样做:

strsplit("This is a sentence. This is a question, right? Yes! It is.",
         "\\. *|, |\\? *|! *")
#[[1]]
#[1] "This is a sentence" "This is a question" "right"             
#[4] "Yes"                "It is"

正如 thelatemail 指出的,这更简单:

strsplit("This is a sentence. This is a question, right? Yes! It is.",
     "[,.:;?!]\\s*")  # \\s* represents a space character appearing 0 or more times

您需要对某些被解释为元字符的字符进行转义。这就是为什么您会在.? 前面看到\\| 是一种“或”。

【讨论】:

  • strsplit(my_string, "[,.:;?!](\\s+|$)") 可能比处理所有转义等更简单。
  • @thelatemail 好电话,我添加了你的建议,除了* 而不是+
【解决方案2】:

你可以使用这个模式来获得你的输出

        string input = @"This is a sentence. This is a question, right? Yes! It is.";
        string pattern = @"[, . : ; ]";

        foreach (string result in Regex.Split(input, pattern))
        {
            Console.WriteLine("'{0}'", result);
        }

请查看控制台是否得到正确的结果。

【讨论】:

  • 你应该转义你的.,添加!,并从你的模式中删除空格。
  • @Joseph 您知道问题出在 R 中,而且并非所有 C# 中的正则表达式实现都存在于 R 中,反之亦然?一般来说,如果是关于 R 的问题,你应该在 R 中回答问题,如果是关于 C# 的问题,你应该回答 C# 中的问题,如果它们是在 python 中的,你应该在 python 中回答。
  • @jerry 很抱歉这个错误,从现在开始会处理这个问题
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2019-03-15
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多