Home > database >  how to count specific amount of question marks with regex
how to count specific amount of question marks with regex

Time:08-24

I am trying to create a regex pattern to match a specific number (3) of question marks in a sentence.

My regex is to check if a sentence has three question marks between to digits (the digits have to sum 10 between both, but thats something else and there can be string characters between them), like so "aabc9??nnh?a1".

I have something that is more or less working, but is not exactly how I wanted to be:

function QuestionsMarks(str) {
  let check = str.match(/\d[\w\?]*?\d/g); // '7??sss?a3', '1??????5'. I would like only '7??sss?a3'
  // console.log('check',check)
  
  return str;
}

console.log(QuestionsMarks("acc?7??sss?a3rr1??????5"
));

My end goal is to return a boolean if certain conditions are met inside the algo.

Thanks for your help and comments :)

CodePudding user response:

For matching the 3 question marks and 2 digits with at least a non digit in between to sum them, you could write the pattern as:

^(?=[a-z_?]*\d[a-z_?] \d[a-z_?]*$)\w*(?:\?\w*){3}\w*$
  • ^ Start of string
  • (?=[a-z_?]*\d[a-z_?] \d[a-z_?]*$) Assert 2 digits with at least one of a-z _ or ? in between
  • \w*(?:\?\w*){3}\w* Match 3 question marks
  • $ End of string

See a regex demo.

const regex = /^(?=[a-z_?]*(\d)[a-z_?] (\d)[a-z_?]*$)\w*(?:\?\w*){3}\w*$/i;
[
  "aabc9??nnh?a1",
  "7??sss?a3",
  "77??sss?a",
  "7??s4ss?a",
  "1??????5"
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    const sum = parseInt(m[1])   parseInt(m[2]);
    console.log(`The sum for ${s} is: `   sum);
  } else {
    console.log(`No match for ${s}`);
  }
})

CodePudding user response:

You can use {3} to require something of 3. That something is an optional series of non-question marks (that are not digits either) followed by a question mark, so (?:[^\d?]*\?){3}:

const regex = /(\d)(?:[^\d?]*\?){3}[^\d?]*(\d)/;
const tests = ["7??sss?a3", "1??????5", "acc?7??sss?a3rr1??????5"];
for (const test of tests) {
  const m = test.match(regex);
  const result = m ?  m[1]    m[2] : "No match";
  console.log(test, "=>", result);
}

  • Related