Is there a way to select string before a pattern in regex?

Viewed 110

I want to extract These are words before hashtag from the below line:

* These are words before hashtag  #work/abc/xyz/123

I have tried \#.*, which highlights everything after #hashtag. How can I select words before the hashtag using a single regex statement?

2 Answers
^[^#\r\n]*(?= #)

^ = Begin matching from the start.

[^#\r\n]+ = Match at least one character, but not hashes or new line characters.

(?= #) = Match a space and a hash, but don't capture them.

Examples here: https://regex101.com/r/PDWT39/1

You could use a capture group for the chars before the #, and match optional spaces followed by the # after it.

^([^#\r\n]+?)[^\S\r\n]*#

The pattern matches:

  • ^ Start of string

  • ( Capture group 1

    • [^#\r\n]+? Match 1+ times (non greedy) any char except # or a newline
  • ) Close group 1

  • [^\S\r\n]* Match optional spaces without newlines

  • # Match literally (Note that you don't have to escape the \#

Regex demo

Or with a lookahead:

^[^#\r\n]+?(?=[^\S\r\n]*#)

Regex demo

Related