dula
dula

Reputation: 61

Regex Pattern with {^ and ^}

I am trying to write a pattern that matches {^xyz^} as bellow,

@"\b\{\^\S*\^\}\b

But I am not getting success and wondering what is problem with my pattern.

Upvotes: 0

Views: 42

Answers (2)

Andrew
Andrew

Reputation: 7880

I would simply use \{\^(\S*?)\^\}. This way you are capturing the contents between the carets and curly brackets. The ? is to make the * quantifier lazy, so it matches as little characters as possible (in order to prevent matching the beginning of one block until the end of another block in the same line).

With those \b you need a word-type character right before and after the curly braces for the regex to match. Is that really a requirement? Or can there be a space?

Upvotes: 0

anubhava
anubhava

Reputation: 785068

You can use:

@"\{\^([^}]*)\^\}"

and extract captured group #1 for your string.

  • Use a captured group to get the substring you want to extract from a larger match.
  • Word boundaries or \b won't work here because { and } are non-word characters.
  • Use of negated character class [^}]* is more efficient and accurate than greedy \S*.

Upvotes: 1

Related Questions