1

I'm want to apply a regex on a string like this word in $ctrl.words Want to find if the string has in and one string after and one before.

I try with this regex [a-zA-Z\\d]+\\s+in\\s+[a-zA-Z\\d]+', but the problem are the special characters from $ctrl.words, the regex always return false. The result what i want is true for string like this fruit in $ctrl.fruits letter in $ctrl.alphabet

And false for strings like fruit in $ctrl.fruits anything else letter in $ctrl.alphabet anithing else

7
  • 2
    Use /^\S+\s+in\s+\S+$/. Commented Mar 1, 2018 at 18:18
  • What do you mean if the string has in and "one string after and one before?" Do you mean that there needs to be characters before and after the in - as separate words? Does the in need to have spaces around it? Commented Mar 1, 2018 at 18:18
  • Yes i'm need separate words before and after the in, and need have spaces too Commented Mar 1, 2018 at 18:21
  • Why are you escaping your backslashes? [a-zA-Z\\d] for example matches alphabetical characters, \, and d (redundantly) Commented Mar 1, 2018 at 18:23
  • 1
    @PatrickRoberts Backslashes should be doubled in RegExp constructor notation, when regex delimiters are not used. Commented Mar 1, 2018 at 18:24

1 Answer 1

2

Since you need to match a string that only consists of two non-whitespace char chunks separated with in enclosed with whitespaces, you may use

/^\S+\s+in\s+\S+$/

See the regex demo

Details

  • ^ - start of string
  • \S+ - `+ non-whitespace chars
  • \s+in\s+ - an in substring enclosed with 1 or more whitespaces
  • \S+ - `+ non-whitespace chars
  • $ - end of string.

JS demo:

var strs = ['fruit in $ctrl.fruits', 'letter in $ctrl.alphabet', 'fruit in $ctrl.fruits anything else', 'letter in $ctrl.alphabet anithing else' ];
var rx = /^\S+\s+in\s+\S+$/;
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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