1

Given an pattern by a user, such as [h][a-z][gho], and a string "gkfhxhk" I'm trying to see if the string contains the pattern.

The pattern means that the first letter would be 'h', the next letter can be any letter from a-z, and the 3rd letter can be either 'g' or 'h' or 'o'. This is supposed to work for any pattern. So another pattern could be [y][b-f][jm].

First I tried to use nested for loops to create a list of all possible strings but that didn't work. Then I tried using RegExp where I pass in the pattern but I'm not quite sure if I'm approaching that the right way:

let string = "gkfhxhk";
// pattern [h][a-z][gho]

let re = new RegExp('ha-zg|h');

let result  = re.match(re);

This just returns a null in the result. Any ideas on how to do this?

6
  • 1
    You need to use proper reg ex syntax: /^h[a-z][g|h|o]$/ should do the trick. Commented Sep 9, 2019 at 18:20
  • 2
    @ChrisG: Why are you puting pipe in the character class? OP doesn't want to match pipe. Commented Sep 9, 2019 at 18:21
  • 2
    Also the anchors are not needed as OP is willing to match pattern anywhere in string not just the complete string Commented Sep 9, 2019 at 18:23
  • @ChrisG The pattern given by the OP is valid regex, although putting a single character within a character set is admittedly a bit awkward. Commented Sep 9, 2019 at 18:24
  • Just put your pattern in the regex constructor: let re = new RegExp('h[a-z][gho]'); or let re = /h[a-z][gho]/; Commented Sep 9, 2019 at 18:28

1 Answer 1

2

This is exactly the type of problem regex was designed to solve. Your syntax is just wrong. This site is an excellent resource for learning regex. As for this specific example, the pattern you want is h[a-z][gho]. (The form [h][a-z][gho] works as well, but the brackets around h are unnecessary.) And in JavaScript, a regex pattern is a special literal, written with // instead of "".

var re = /h[a-z][gho]/;

var str1 = "gkfhxhk";

var str2 = "gkajflh";

console.log(str1.match(re));

console.log(str2.match(re));

Note that match returns a list of matches, not a simple true/false value. It returns null when there are no matches.

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

4 Comments

Why do you anchor the regex?
@Toto From the question: "The pattern means that the first letter would be 'h'".
The first letter of the pattern, not of the string!
I like using /regex/.test('string') because it does return a true/false value which I find a bit easier to reason about than match. :)

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.