1

I am trying to use regular expression on a custom set of data, it can occur in any order

var str= "keyword2 : (content2),  sas, keyword1 : (content1)"

or

 var str= "keyword2 : (content2),  app, keyword1 : (content1), sos, key word : (content) " 

each key is separated using commas. I am trying to find the odd ones out of this, the one which doesnt have pair, like sas, app, sos and return it in to an array using regular expression.. Is it possible to acheive it using regex?

Sam
  • 49
  • 5
  • 2
    Not really suitable for a RE, .split(",") to arrays then; http://stackoverflow.com/questions/1187518/javascript-array-difference – Alex K. Sep 06 '12 at 13:43
  • I agree, trying to use a regex here seems to indicate a possible belief that they are a silver bullet; see: http://en.wikipedia.org/wiki/No_Silver_Bullet – Dexygen Sep 06 '12 at 13:51

1 Answers1

2

Sure, you are looking for following regexp: /\w+\s?(?=,|$)/igm.

var reg = /\w+\s?(?=,|$)/igm;

var str = "keyword2 : (content2), app, keyword1 : (content1), sos, key word : (content), das";

console.info(str.match(reg));

Here is working demo: http://jsfiddle.net/tvUaK/139/, remember to open firebug console to see the output.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
  • Ive used match() and it returned with coma.. it only returns the first occurence – Sam Sep 06 '12 at 13:50
  • is there a proper way to return without commas?? – Sam Sep 06 '12 at 13:56
  • there is problem when the input format is like "keyword2 : (content2), app, keyword1 : (content1), sos, key word : (content), das" – Sam Sep 06 '12 at 14:09
  • one more doubt,what if the input was like the one ive updated in jsfiddle and wanted the output as app,sos,das,sad – Sam Sep 06 '12 at 14:37
  • Sorry but now I can't see any pattern... there are any commas, maybe you would like get all 3-letters words? Anyway, now it looks like completely new task for me :) – IProblemFactory Sep 06 '12 at 19:14
  • the patttern is like remove all words before : till a space occurs and all words after : till ) occurs.. http://jsfiddle.net/tvUaK/141/ – Sam Sep 07 '12 at 02:33
  • 1
    Here is my regexp http://refiddle.com/353 but unfortunatelly using with JS it also return a lot of empty string, so it were necessary use a loop to clean up... here is completely code http://jsfiddle.net/tvUaK/144/ – IProblemFactory Sep 07 '12 at 07:33
  • replace(/[^:\s]+:\([^)]*\)\s* /g, ''); – Sam Sep 07 '12 at 08:40