0

I would like to match the following term in JavaScript using regex.

String = 'abc AND def AND igk AND lmn'

Terms to match: the word before and after first AND.

For example in the above string the match part will be : abc AND def.

I want to do it in JavaScript. So I will call

string.match(/regex to use/)

and assign it to a var.

Any suggestions please.

EDIT:

the string can be of form like:

    string = 'AND abc';
    string = 'abc AND';
    string = 'abc def AND igk lmn';
    string = 'abc def AND';
    string = 'AND igk lmn';

Appreciate your help in this regard.

3
  • So the words before/after are optional? Or should there only be a match if both words are actually present? Could there be a string 'AND' (and if so, what should happen)? Commented May 22, 2012 at 12:09
  • Are you interested in matching abc if your string is 'abc' (no AND at all)? Commented May 22, 2012 at 12:19
  • if i dont have word before or after AND, no issues, i will get blank. If only AND present my both words will be blank. So words are optional can be present or absent. I will validate them after and have null passed. Commented May 22, 2012 at 12:38

2 Answers 2

3

You can try this regex:

/(\w+\s+AND\s+\w+)/

EDIT (after having read your last update): if left and right terms are optional, use the following regex instead:

/(?: (\w+) \s+)? AND (?: \s+ (\w+))?/x
Sign up to request clarification or add additional context in comments.

4 Comments

You need to remove the ^ or this will fail if there is more than one word before the first AND.
I have made the edit; as long as you don't use the /g modifier, this regex will find the first occurrence of AND plus the two words around it (provided a "word" is defined as "as series of ASCII alphanumeric characters").
Thanks, Tom. I put ^ because it was unclear before the OP's last edit what exactly needed to be matched.
Thanks :0 to match my cases i am using it as: /(\w*\sAND\s*\w)/
1

A slight improvement on Igor's version :

   var m = str.match (/(\w+)\s+AND\s+(\w+)/);
   // word before AND in m[1], word after AND in m[2] 

Automagically extracts the two words.

1 Comment

i am using it as: /(\w*)\sAND\s*(\w)/. Thank you

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.