[Solved] Regular expression to match group of consecutive characters [duplicate]


You might use a positive lookahead and test if the string contains /*?

If so, match any character one or more times .+ from the beginning of the string ^ until the end of the string $

^(?=.*\/\*).+$

Explanation

  • ^ Begin of the string
  • (?= Positive lookahead that asserts what is on the right
    • .*\/\* Match any character zero or more time and then /*
  • ) Close positive lookahead
  • .+ Match any character one or more times
  • $ End of the string
const strings = [
  "Hello NO MATCH",
  "123 NO MATCH",
  "/* HELLo MATCH",
  "/*4534534 MATCH",
  "test(((*/*"
];
let pattern = /^(?=.*\/\*).+$/;

strings.forEach((s) => {
  console.log(s + " ==> " + pattern.test(s));
});

I think you could also use indexOf() to get the index of the first occurence of /*. It will return -1 if the value is not found.

const strings = [
  "Hello NO MATCH",
  "123 NO MATCH",
  "/* HELLo MATCH",
  "/*4534534 MATCH",
  "test(((*/*test",
  "test /",
  "test *",
  "test /*",
  "/*"
];
let pattern = /^(?=.*\/\*).+$/;

strings.forEach((s) => {
  console.log(s + " ==> " + pattern.test(s));
  console.log(s + " ==> " + (s.indexOf("/*") !== -1));
});

1

solved Regular expression to match group of consecutive characters [duplicate]