jdross
jdross

Reputation: 1206

Regex pattern in C# with empty space

I am having issue with a reg ex expression and can't find the answer to my question.

I am trying to build a reg ex pattern that will pull in any matches that have # around them. for example #match# or #mt# would both come back.

This works fine for that. #.*?# However I don't want matches on ## to show up. Basically if there is nothing between the pound signs don't match.

Hope this makes sense. Thanks.

Upvotes: 2

Views: 287

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

Please use + to match 1 or more symbols:

#+.+#+

UPDATE: If you want to only match substrings that are enclosed with single hash symbols, use:

(?<!#)#(?!#)[^#]+#(?!#)

See regex demo

Explanation:

  • (?<!#)#(?!#) - a # symbol that is not preceded with a # (due to the negative lookbehind (?<!#)) and not followed by a # (due to the negative lookahead (?!#))
  • [^#]+ - one or more symbols other than # (due to the negated character class [^#])
  • #(?!#) - a # symbol not followed with another # symbol.

Upvotes: 5

Blue0500
Blue0500

Reputation: 725

Instead of using * to match between zero and unlimited characters, replace it with +, which will only match if there is at least one character between the #'s. The edited regex should look like this: #.+?#. Hope this helps!

Edit

Sorry for the incorrect regex, I had not expected multiple hash signs. This should work for your sentence: #+.+?#+

Edit 2

I am pretty sure I got it. Try this: (?<!#)#[^#].*?#. It might not work as expected with triple hashes though.

Upvotes: 2

scurrie
scurrie

Reputation: 403

Try:

[^#]?#.+#[^#]?

The [^ character_group] construction matches any single character not included in the character group. Using the ? after it will let you match at the beginning/end of a string (since it matches the preceeding character zero or more times. Check out the documentation here

Upvotes: 1

Related Questions