CuriousBuddy
CuriousBuddy

Reputation: 197

Fetch values between two [] from a string using Regular expressions

I have a string like as folows :

"channel_changes":[[1313571300,26.879846,true],[1313571360,26.901025,true]]

I want to extract each string in angular brace like 1313571300, 26.879846, true

through regular expression.

I have tried using

string regexPattern = @"\[(.*?)\]";

but that gives the first string as [[1313571420,26.901025,true] i.e with one extra angular brace.

Please help me how can I achieve this.

Upvotes: 0

Views: 296

Answers (3)

Neil Barnwell
Neil Barnwell

Reputation: 42165

This seemed to work in Expresso for me:

\[([\w,\.]*?)\]

Literal [
[1]: A numbered capture group. [[\w,.]*?]
- Any character in this class: [\w,.], any number of repetitions, as few as possible
Literal ]

The problem seemed to be the "." in your regex - since it was picking up the first literal "[" and considering the following "[" in your input to be valid as the next character.

I constrained it to just alphanumeric characters, commas and literal full-stops (period mark), since that's all that was present in your example. You could go further and really specify the format of the data inside those inner square brackets assuming it's consistent, and end up with something more like this:

\[[0-9.]+,[0-9.]+,(true|false)\]

Example C# code:

var matches = Regex.Matches("\"channel_changes\":[[1313571300,26.879846,true],[1313571360,26.901025,true]]", @"\[([\w,\.]*?)\]");

foreach (var match in matches)
{
    Console.WriteLine(match);
}

Upvotes: 1

stema
stema

Reputation: 93086

Try this

\[([^\[\]]*)\]

See it here online on Regexr

[^\[\]]* is a negated character class, means match any character but [ and ]. With this construct you don't need the ? to make your * ungreedy.

Upvotes: 0

sun_che
sun_che

Reputation: 1

Try this:

@"\[+([^\]]+)\]+"

"[^]]+" - it means any character except right square bracket

Upvotes: 0

Related Questions