user6206542
user6206542

Reputation:

Regular Expression that matches on values after a pipe in between brackets

I'm still learning a lot about regex, so please forgive any naivety.

I've been using this site to test: http://www.systemtextregularexpressions.com/regex.match

Basically, I'm having issues writing a regular expression that will match on any value after a pipe in between brackets.

Given an example string of:

"<div> \n [dont1.dont2|match1|match2] |dont3 [dont4] dont5. \n </div>"

Expected output would be a collection:

match1,
match2 

The closest I've been able to get so far is:

(?!\[.*(\|)\])(?:\|)([\w-_.,:']*)

Above gives me the values, including the pipes, and dont3.

I've also tried this guy:

\|(.*(?=\]))

but it outputs:

|match1|match2

Upvotes: 0

Views: 1247

Answers (3)

Steven Doggart
Steven Doggart

Reputation: 43743

Here's one way of doing it:

(?<=\[[^\]]*\|)[^\]|]*

Here's the meaning of the pattern:

  • (?<=\[[^\]]*\|) - Lookbehind expression to ensure that any match must be preceded by an open bracket, followed by any number of non-close-bracket characters, followed by a pipe character
    • (?<= ... ) - Declares a lookbehind expression. Something matching the lookbehind must immediately precede the text in order for it the match. However, the part matched by the lookbehind is not included in the resulting match.
    • \[ - Matches an open bracket character
    • [^\]]* - Matches any number of non-close-bracket characters
    • \| - Matches a pipe character
  • [^\]|]* - Matches any number of characters which are neither close brackets nor pipe characters.

The lookbehind is greedy, so it will allow for any number of pipes between the open bracket and the matching text.

Upvotes: 1

Aminah Nuraini
Aminah Nuraini

Reputation: 19146

Try this:

^<div>\s*[^|]+|([^|]+)|([^|]+)

Upvotes: 0

Scott Weaver
Scott Weaver

Reputation: 7351

try this:

\[.*?(?:\|(?<mydata>.*?))+\]

note: the online tool will only show you the last capture inside a quantifed () for a given match, but .NET will remember each capture of a group that matches multiple times

Upvotes: 0

Related Questions