1
var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str2 = "I dont have any two";

for these string need to find a reg like it should match string starts with "I" AND contains "one" or "two".

var regx = "/^I/";        //this starts with I
var regx = "/(one|two)/";  //this match one or two

But how to combain both with an AND ?

So str1.test(regx) should be false.

Sarath
  • 8,762
  • 11
  • 46
  • 80

3 Answers3

4

Just match any character between I and one

var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str3 = "I dont have any two";

var regx = /^I.*(one|two)/

console.log(regx.test(str)) // True
console.log(regx.test(str1)) // False
console.log(regx.test(str2)) // False
console.log(regx.test(str3)) // True

Here a fiddle to test

Fractaliste
  • 5,388
  • 9
  • 39
  • 79
  • Nice, all I was searching for this ".*" its misleading in this http://stackoverflow.com/questions/469913/regular-expressions-is-there-an-and-operator – Sarath Sep 15 '14 at 13:54
  • The title of the question talks about "one" and "two" as *words*, so you might want to throw that option in ("I have none" would match the above). – T.J. Crowder Sep 15 '14 at 13:55
  • And it returns true for `It is one` not sure if OP is fine with this. – anubhava Sep 15 '14 at 13:57
  • 1
    @anubhava Sure, maybe I should add spaces characters around `I` and `(one|two)` – Fractaliste Sep 15 '14 at 14:00
  • 1
    You do not need to add spaces. using word boundaries should suffice: `/^I\b.*\b(one|two)\b/` – Casimir et Hippolyte Sep 15 '14 at 14:02
  • no Casimer. OP wants to match the lines which starts with `I` that's all. So no need for word boundary after `I`. And also `\b(one|two)` will also match `one` in `:one` – Avinash Raj Sep 15 '14 at 14:05
2

different approach ...

var regx1 = /^I/;        //this starts with I
var regx2 = /(one|two)/;  //this match one or two

// starts with "I" AND contains "one" or "two".
var match = regx1.test(str1) && regx2.test(str1)
Neverever
  • 14,897
  • 3
  • 30
  • 48
1

It would be better if you add a word boundary.

var regx = /^I.*? (?:one|two)( |\b).*$/;

DEMO

Avinash Raj
  • 166,785
  • 24
  • 204
  • 249