views:

77

answers:

4

Hi,

I have a requirement to filter out some of the specified strings in a given line using regx.. This can be easily achievale using string.macth(). But my requirement is little bit tricky.

I have set of keywords, that needs to be identified in a given string. (My input string contains only one expected keyword). I have to form the regX string and that will find which keyword is available in my input string .

Below the sample input and output

  var InString ="one_sam_get_2384823_34534";
  var keyList  = "one|two|three|four|five";

here my expected result is one

or

  var InString ="odfdfg_three_get_2384823_34534";
  var keyList  = "one|two|three|four|five";

here my expected result is three

earlier i used something like this "/^one/i" to find out the single keyword occurance.

But i am struck up in this multi keyword approach. I appreaciate any guidance.

Cheers

Ramesh Vel

+2  A: 

You can use the keyList to create a RegExp object:

InString.match(new RegExp(keyList, "i"))
Gumbo
Yeah, I believe this is the best way. +1
Cerebrus
thanks gumbo, it works.. as CMS suggested, i read the matching keyword using Out[0]
Ramesh Vel
Almost ... "onetwo_three".match(new RegExp("one|two|three", "i"))[0] will return "one", which is not what you want.
Vinay Sajip
yes thats wat i want, cant directly use onetwo_three".match(new RegExp("one|two|three", "i"))[0].. it throws an exp at [0] if no keyword found... so i use a tem var to check if null then i get it from 0th idx...
Ramesh Vel
A: 

Use a regex of the form var regex = /(one|two|three)/;

mhansen
A: 

why don't you user a regular expression like

"/(one|two|three|four|five)/i"

Cheers

RageZ
+1  A: 

Edit:

function findKey (input, keyList) {
  var result = input.match(new RegExp(keyList));

  if (result) {
    return result[0];
  }
}
CMS
my requirement is not to pass the keywords indivitually (re.exec(inString)[0]), i have to pass all the keywords in a single expreassion and execute it.. because am not sure abt the keywords thats to be present in the inString
Ramesh Vel
sorry cms.. misunderstood that... urs work perfectly.. thank you very much
Ramesh Vel