I need a regex in R to exclude 1 or 2-character words, but which does not treat hyphens as word boundaries. Here is an example:

z <- c("regulatory protein SR-B1 na na na na", "Dr Foo is na Editor-in-chief", "na P3 protein is popular na na")  

The intended 'gsub' would produce the result

[1] "regulatory protein SR-B1" " Foo Editor-in-chief" "P3 protein popular"

This is not produced from the gsub statements below. Instead:

A - 2-character segments unintentionally dropped from hyphenated words (and hyphens kept).

B - 2-character segments unintentionally dropped within hyphenated words (hyphens also dropped):

C - Produces: Error: '-' is an unrecognized escape in character string starting "" *\b[[-"

D - Nothing dropped or changed:

gsub(" *\\b[[:alpha:]]{1,2}\\b *", " ", z) # A

gsub(" *\\b[-[:alpha:]]{1,2}\\b *", " ", z)  # B

gsub(" *\\b[[\-][:alpha:]]{1,2}\\b *", " ", z)  # C

gsub(" *\\b[[\\-][:alpha:]]{1,2}\\b *", " ", z) # D  

Input would be much appreciated.


Try this

gsub(" *\\b(?<!-)\\w{1,2}(?!-)\\b *", " ", z, perl=T)
| improve this answer | |
  • $\begingroup$ This really helped, and provided the syntax frame I needed. I need to exclude 1 or 2 'alpha-character' words (e.g, 'na') and keep 2 character 'alphanumeric' words (e.g., 'P3'), as in the desired output example above. The substitution of '[[:alpha:]]' for '\\w' in the statement you provide, does the trick. Decoding your syntax taught me about 'Negative lookbehind' in regex, which is super useful. I learned something today. > gsub(" *\\b(?<!-)[[:alpha:]]{1,2}(?!-)\\b *", " ", z, perl=T) $\endgroup$ – North of 49 Nov 8 '17 at 1:08
  • $\begingroup$ good to hear it helped ,but no idea why this is downvoted :) . Perhaps putting downvote for new joinees seems to be the tradition $\endgroup$ – niths4u Nov 8 '17 at 15:26

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