Regrex string to match a list in R

Viewed 66

I'm looking for a string match finder to test if the following string in the output can be extracted from the list stringsToTest.

I have a regex string but can't get the right combination. There are a lot of possibilites for this.

My actual list is about 140,000 strings long and I only want this combination to find:

stringsToTest = list("abc/a3d)-1-B-3-B","dec/d93)-B-1-3",
                     "vdiek/asdf899)-1-B-B-B-1-3-4","avd/asd/vde)-1-B-3-4",
                     "ab33/dfv)-B-12-B","abc/ade)-1")

I use grepl b/c it gives me a true or false for the following string

grepl(stringsToTest, #pattern=#pattern="([:alnum:]+\\/){2}\\){1}a\\-]{1}([:alnum:]*a\\-]){3}.*$")){
    pattern="[:alnum:]+[:punct:]+[:alnum:]+[:punct:]+[:alnum:]+[:punct:]+[:alnum:]+[:punct:]+[:alnum:]+[:punct:]+[:alnum:].*$")
#[1] FALSE FALSE FALSE FALSE FALSE FALSE

My output I would like would be. The foward slash, parethesis, and hyphons need to be exactlly the same. My cut off is a forward slash followed by a parathesis followed by three hyphons. I will except more hyphons beyond this if there are as shown in the example.

Expected output:

[1] TRUE TRUE TRUE FALSE TRUE FALSE
1 Answers

You can use

^[[:alnum:]]+/[[:alnum:]]+\)(?:-[[:alnum:]]+){3}

See the regex demo. Details:

  • ^ - start of string
  • [[:alnum:]]+ - one or more letters or digits
  • / - a / char
  • [[:alnum:]]+ - one or more letters/digits
  • \) - a ) char
  • (?:-[[:alnum:]]+){3} - three occurrences of a - and then one or more letters/digits sequences.

See the R demo:

stringsToTest = list("abc/a3d)-1-B-3-B","dec/d93)-B-1-3",
                     "vdiek/asdf899)-1-B-B-B-1-3-4","avd/asd/vde)-1-B-3-4",
                     "ab33/dfv)-B-12-B","abc/ade)-1")
grepl(stringsToTest, 
     pattern="^[[:alnum:]]+/[[:alnum:]]+\\)(?:-[[:alnum:]]+){3}")
## => [1]  TRUE  TRUE  TRUE FALSE  TRUE FALSE
Related