1

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.

4 Answers 4

3

You can use the keyList to create a RegExp object:

InString.match(new RegExp(keyList, "i"))
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, I believe this is the best way. +1
thanks gumbo, it works.. as CMS suggested, i read the matching keyword using Out[0]
Almost ... "onetwo_three".match(new RegExp("one|two|three", "i"))[0] will return "one", which is not what you want.
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...
1

Edit:

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

  if (result) {
    return result[0];
  }
}

2 Comments

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
sorry cms.. misunderstood that... urs work perfectly.. thank you very much
0

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

Comments

0

why don't you user a regular expression like

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

Cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.