Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

Regular expression for splitting a string and add it to an Array

I have a string which is in the following format:

[0:2]={1.1,1,5.1.2}

My requirement here is to split the values inside curly braces after = operator, and store them in to a string array. I had tried to split part by using Substring() and IndexOf() methods, and it worked. But I needed a cleaner and elegant way to achieve this via regular expressions.

Does anybody having clues to achieve my requirement?

Upvotes: 0

Views: 163

Answers (4)

Civa
Civa

Reputation: 2176

if you want it using Regex

Dim s() As String=Regex.match(str,"(={)(.*)(})").Groups(1).Tostring.split(',');

Upvotes: -1

Sepster
Sepster

Reputation: 4849

Dim s As String = "[0:2]={1.1,1,5.1.2}";

Dim separatorChar as char = "="c;
Dim commaChar as char = ","c;
Dim openBraceChar as char = "{"c;
Dim closeBraceChar as char = "}"c;

Dim result() as String = 
  s.Split(separatorChar)(1)
   .trim(openBraceChar)
   .trim(closeBraceChar)
   .split(commaChar);

(assuming it works! Typed on an iPad so can't verify syntax easily, but principal should be sound).

EDIT: updated to VB as downvoted for showing working .net methods in c# syntax.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

Here is your fully RegEx solution:

Dim input As String = "[0:2]={1.1,1,5.1.2}"

Dim match = Regex.Match(input, "\[\d:\d\]={(?:([^,]+),)*([^,]+)}")

Dim results = match.Groups(1).Captures.Cast(Of Capture).Select(Function(c) c.Value).Concat(match.Groups(2).Captures.Cast(Of Capture).Select(Function(c) c.Value)).ToArray()

Don't think it is more readable then standard split:

Dim startIndex = input.IndexOf("{"c) + 1
Dim length = input.Length - startIndex - 1
Dim results = input.Substring(startIndex, length).Split(",")

Upvotes: 2

sloth
sloth

Reputation: 101032

You could use a regular expression to extract the values inside the curly braces, and then use an ordinary Split:

Regex.Match("[0:2]={1.1,1,5.1.2}", "{(.*)}").Groups(1).Value.Split(","c)

Upvotes: 1

Related Questions