R count number of commas and string

前端 未结 4 1042
遇见更好的自我
遇见更好的自我 2021-01-17 19:25

I have a string:

    str1 <- \"This is a string, that I\'ve written 
        to ask about a question, or at least tried to.\"

How would

4条回答
  •  自闭症患者
    2021-01-17 19:39

    The general problem of mathcing text requires regular expressions. In this case you just want to match specific characters, but the functions to call are the same. You want gregexpr.

    matched_commas <- gregexpr(",", str1, fixed = TRUE)
    n_commas <- length(matched_commas[[1]])
    
    matched_ion <- gregexpr("ion", str1, fixed = TRUE)
    n_ion <- length(matched_ion[[1]])
    

    If you want to only match "ion" at the end of words, then you do need regular expressions. \b represents a word boundary, and you need to escape the backslash.

    gregexpr(
      "ion\\b", 
      "ionisation should only be matched at the end of the word", 
      perl = TRUE
    )
    

提交回复
热议问题