Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex Parsing Question

Status
Not open for further replies.

Skie

Programmer
Jun 21, 2004
475
0
0
US
I'm separating lines of data it into key/value pairs. I have a regex to do this, but I'd like to expand it to be able to parse values with spaces.

Code:
Shared Sub ByDelimiter(ByVal input As String, ByRef dict As Dictionary(Of String, String))
  If String.IsNullOrEmpty(input) Then
    Throw New ArgumentNullException("input")
  End If
  If dict Is Nothing Then
    Throw New ArgumentNullException("dict")
  End If
  Dim pattern As String = "(?<key>\S+)=(?<value>\S*)"
  For Each m As Match In Regex.Matches(input, pattern)
    dict.Add(m.Groups("key").Value, m.Groups("value").Value)
  Next
End Sub

So if I have a line consisting of...
A=1 B=2 C=3 + 3 4=NOTHING 5=SOMETHING ELSE

My dictionary would be...
A,1
B,2
C,3
4,NOTHING
5,SOMETHING

I'd like the dictionary to be...
A,1
B,2
C,3 + 3
4,NOTHING
5,SOMETHING ELSE
 
I think I figured it out. After a little playing around and testing it looks like this would work.

\S+=(\S(?!\S+=)\s?)*

If there's a simpler expression or if you see something that's wrong with the expression let me know.
 
It wasn't quite working, plus I wanted to stop gathering after a double-space. It's a bit longer but is parsing keys and values correctly now.

(?<key>\S+)=(?<value>((?!(\S+=|\s{2}))\S*\s?)*)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top