1

I am trying to extract Twitter hashtags from text using regex in R, using str_match_all from the "stringr" package.

The problem is that sometimes the hashtag gets truncated, with a horizontal ellipsis character appended to the end of the text string, as shown in this example:

str_match_all("hello #goodbye #au…","#[[:alnum:]_+]*[^…]")[[1]]

I can successfully extract a list of hashtags, using the above code, but I want to exclude hashtags that are truncated (i.e. that have a horizontal ellipsis character).

This is frustrating as I have looked everywhere for a solution, and the above code is the best I can come up with, but clearly does not work.

Any help is deeply appreciated.

2
  • @Pascal My apologies - it is the "stringr" package Jun 11, 2015 at 8:21
  • @stribizhev I am getting both substrings as in the OP's output
    – akrun
    Jun 11, 2015 at 8:42

1 Answer 1

1

I suggest using regmatches with regexpr and the #[^#]+(?!…)\\b Perl-style regex:

x <- "#hashtag1 notHashtag #hashtag2 notHashtag #has…"
m <- gregexpr('#[^#\\s]+(?!…)\\b', x, perl=T)
// or m <- gregexpr('#\\w+(?!…)\\b', x, perl=T)
// or m <- gregexpr('#\\S+(?!…)\\b', x, perl=T)
regmatches(x, m)

See demo on CodingGround

The regex means:

  • # - Literal #
  • [^#]+ - 1 or more characters other then # (or \\w+ to match alphanumerics and underscore only, or \\S+ that will match any number of non-whitespace characters)
  • (?!…)\\b - Match a word boundary that is not preceded by a

Result of the above code execution: [1] "#goodbye"

3
  • Hi @stribizhev, thanks, this is on the right track. However, when I try this: x <- "#hashtag1 notHashtag #hashtag2 notHashtag #has…" regmatches(x, regexpr('#[^#]+(?!…)\\b', x, perl=T)) It gives the following output: [1] "#hashtag1 notHashtag" I want to match these two words: "#hashtag1" and "#hashtag2". However, it is not achieving this. Jun 11, 2015 at 12:41
  • 1
    I have edited the answer. We need to either use a more precise negated character class [^#\\s], or switch to \\w that only allows [a-zA-Z0-9_]. Or maybe even allow anything but a whitespace: #\\S+(?!…)\\b. Jun 11, 2015 at 12:48
  • Thank you! I can confirm the answer works perfectly, and provides several options for fine-tuning, so I am highly appreciative. Many thanks. Jun 11, 2015 at 13:11

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.