How can convert this regex to R regex and regex R usage

Viewed 73

I tested with regex101 but my code does not work in R. What can I do? Please help me.

(?<=\[).+?(?=\])

I have includes >XP_002499978.1 predicted protein [Micromonas commoda] type of fasta file and I need >Micromonas_commoda_XP_002499978.1 type of info.

I need to delete and change parenthesis info.

1 Answers

You can use

x <- ">XP_002499978.1 predicted protein [Micromonas commoda]"
x <- gsub("(?:\\G(?!^)|\\[)[^][\\s]*\\K\\s+", "_", x, perl=TRUE) # Replace spaces in [ ]
## [1] ">XP_002499978.1 predicted protein [Micromonas_commoda]"
sub("^>(\\S+).*\\[([^][]*)].*", ">\\2_\\1", x)  # Reformat the string 
## => [1] ">Micromonas_commoda_XP_002499978.1"

There are two actions here:

  • gsub("(?:\\G(?!^)|\\[)[^][\\s]*\\K\\s+", "_", x, perl=TRUE) replaces all whitespace chunks inside square brackets with a single _
  • sub("^>(\\S+).*\\[([^][]*)].*", ">\\2_\\1", x) reformats the string.

See the regex #1 demo and the regex #2 demo.

Related