Brani
Brani

Reputation: 6784

Lookahead in regular expression

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.

Upvotes: 1

Views: 216

Answers (2)

anubhava
anubhava

Reputation: 785286

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

Upvotes: 2

dax90
dax90

Reputation: 1118

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

str_extract(var.descr, perl("^[^/]+"))

Upvotes: 1

Related Questions