Tarik
Tarik

Reputation: 81711

Regex Question to Grab Keys

I have this kinda template text :

Hello {#Name#},

Thanks for coming blah on {#Date#} and we love to see you again here with {#President#}

So I am trying to get {#...#} templates parts and put them into an array.

But my expression didn't work :

\b(?<=\{\#)(.*)(?=\#\})\b

The result became something like this for this sample text :

{#Something#} Hello {#Brand#} 

Result :

Something#} Hello {#Brand

Upvotes: 4

Views: 146

Answers (2)

Damian Powell
Damian Powell

Reputation: 8775

How about this? {#([^#]+)#}

Here's the example used in a PowerShell script:

$input = "{#Something#} Hello {#Brand#}"

$match = [regex]::Match($input, "{#([^#]+)#}")

$i = 0

while ($match.Success) {
    $i++
    write-host ("Match {0}: '{1}'" -f $i, $match.Groups[1].Value)
    $match = $match.NextMatch()
}

And this is what it outputs:

Match 1: 'Something'
Match 2: 'Brand'

Upvotes: 3

Hun1Ahpu
Hun1Ahpu

Reputation: 3355

Just add ? for laziness like this:

\b(?<=\{\#)(.*?)(?=\#\})\b

*? means that it will search for as few repeats as possible

Upvotes: 4

Related Questions