1

I am trying to use a regular expression in order to extract the part of a string before the first " / " occurrence. In the following example the initial string is "Atomic grouping / possessive qualifiers / conditional and recursive patterns" and i want to get "Atomic grouping"

library(stringr)
var.descr <- "Atomic grouping / possessive qualifiers / conditional and recursive patterns"

I tried the following but it matches the string until the last " / " occurrence (it returns "Atomic grouping / possessive qualifiers")

str_extract(var.descr, perl("^.+(?=\\s/)"))

Any help would be gratefully appreciated.

2 Answers 2

2

You can use lookahead regex like this:

str_extract(var.descr, perl("^.+?(?= / |$)"))

(?= / |$) will make sure either / is followed by the matched text or it matches till end of input.

RegEx Demo

2
  • Thank you. Could you provide a modification in order to get the whole string when there is no " / " in it?
    – Brani
    May 8, 2015 at 15:49
  • Thank you but I dont want to exclude "/", only " / ". For example if there is an "and/or" in the string (before the first " / ") I don't want it to be excluded
    – Brani
    May 8, 2015 at 16:26
1

You can use the "lazy" + with ? after it

str_extract(var.descr, perl("^[^/]+"))
2
  • Thank you. Could you provide a modification in order to get the whole string when there is no " / " in it?
    – Brani
    May 8, 2015 at 15:26
  • Thank you but I dont want to exclude "/", only " / ". For example if there is an "and/or" in the string (before the first " / ") I don't want it to be excluded
    – Brani
    May 8, 2015 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.