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!

Any RegEx experts out there?

Status
Not open for further replies.

sugarflux

Technical User
Aug 14, 2003
111
0
0
GB
Hi

First off apologies if this question is in the wrong place... There is no dedicated RegEx forum and since I'm working in JS and in my experience RegEx is most commonly used in JS - here lies my problem :)

I have a number of search strings that I would like to split into an array. The search is usually separated by spaces, but the search terms can also contain spaces and in this case they are quoted. Here's an example:

SearchTerm1=foo SearchTerm2=bar SearchTerm3="hello world" SearchTerm4="nospacesbutquotedanyway" SearchTerm5=foo,bar

I would like to return as an array:
[0][0]SearchTerm1
[0][1]foo
[1][0]SearchTerm2
[1][1]bar
[2][0]SearchTerm3
[2][1]hello world
[3][0]SearchTerm4
[3][1]nospacesbutquotedanyway
[4][0]SearchTerm5
[4][1]foo,bar

I'm toying with writing a function that first searches the string for quoted chunks, perhaps replacing the spaces inside quotes with an uncommon character in order to split the string by space and replace them back again afterwards. But hoping someone might come up with a magic RegEx to neatly do the job for me!

Thanks in advance,

~S~
 
Hi

Something like this ?
Code:
[blue]>  s = 'SearchTerm1=foo SearchTerm2=bar SearchTerm3="hello world" SearchTerm4="nospacesbutquotedanyway" SearchTerm5=foo,bar'[/blue]
   [red]"SearchTerm1=foo SearchTerm2=bar SearchTerm3="hello world" SearchTerm4="nospacesbutquotedanyway" SearchTerm5=foo,bar"[/red]
[blue]>  result = []; s.replace(/(\S+)=(?:(["'])(.*?)\2|(\S*))/g, function(g0, g1, g2, g3, g4) { result.push([g1, g3 || g4]) })[/blue]
   [red]"undefined undefined undefined undefined undefined"[/red]
[blue]>  result[/blue]
   [blue][b][[[/b][/blue][red]"SearchTerm1"[/red][blue][b],[/b][/blue] [red]"foo"[/red][blue][b]], [[/b][/blue][red]"SearchTerm2"[/red], [red]"bar"[/red][blue][b]], [[/b][/blue][red]"SearchTerm3"[/red][blue][b],[/b][/blue] [red]"hello world"[/red][blue][b]], [[/b][/blue][red]"SearchTerm4"[/red][blue][b],[/b][/blue] [red]"nospacesbutquotedanyway"[/red][blue][b]], [[/b][/blue][red]"SearchTerm5"[/red][blue][b],[/b][/blue] [red]"foo,bar"[/red][blue][b]]][/b][/blue]
Note that if you need escaping, like SearchTerm0="John \"Hannibal\" Smith", that will be harder to solve with regular expression.


Feherke.
feherke.ga
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top