使用单个代码查找": - "或"? - "或". - "或"; - "文本中的位置

  • 本文关键字:文本 位置 单个 查找 代码 r
  • 更新时间 :
  • 英文 :


我试图在问题中找到分隔符的位置问题是,对于不同的问题,分隔符可能不同。有没有一种方法可以找到分隔符位置,无论它是否是不同的

a <- "S4a? How old are you? - 25-34years old."
b <- "S4a. How old are you. - 25-34years old."
c <- "S4a: How old are you: - 25-34years old."
d <- "S4a; How old are you; - 25-34years old."

我可以运行下面的每一个来找到每种类型的分隔符的位置

unlist(gregexpr(pattern ="\? - ", a ))
unlist(gregexpr(pattern =". - ", b ))
unlist(gregexpr(pattern =": - ", c ))
unlist(gregexpr(pattern ="; - ", d ))

它们都返回相同的结果

> unlist(gregexpr(pattern ="\? - ", a ))
[1] 21

我一直在尝试,但收效甚微,因为它只是在中找到了所有东西

unlist(gregexpr(pattern ="\?|\.|; - ", a ))

有办法找到这些标志吗以及"-"在我的搜索模式中。还是需要用"或"-"或"-"或"-">

如有任何帮助,我们将不胜感激。

您需要将更改的字符放在括号中,如下所示:

unlist(gregexpr(pattern ="(\?|\.|;|:) - ", a ))
#21
unlist(gregexpr(pattern ="(\?|\.|;|:) - ", b ))
#21
unlist(gregexpr(pattern ="(\?|\.|;|:) - ", c ))
#21
unlist(gregexpr(pattern ="(\?|\.|;|:) - ", d ))
#21

最新更新