SebastianOS
SebastianOS

Reputation: 55

regex to match a string without whitespaces between two #

I am looking for a regex, which returns a string between two hashtags, but only if between the two # there is no whitespace.

My current regex: \#(.*?)\#

Testcase 1:

'#thisshouldbeparsed# #2 test'
=> thisshouldbeparsed (this is currently correct)

Testcase 2:

'test #2 #thisshouldbeparsed#'

=>2 (this is not correct)

I need a regex which is returning also "thisshouldbeparsed".

Upvotes: 3

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You can use

#([^#\s]*)#

To avoide empty matches, replace * with +:

#([^#\s]+)#

See the regex demo.

Details

  • # - a # char
  • ([^#\s]*) - Group 1: any zero or more chars other than # and whitespace
  • # - a # char.

Upvotes: 1

Related Questions