I'm trying to make a regex that will count every question mark that is inside of quotes. This regex is being tested in javascript but I intend to use it for PHP if that matters. I have something that kind of works but not well enough.
Here it is.
/(\"|\')(([^\"\'\\]|\\.)*)\?(([^\"\'\\]|\\.)*(\"|\'))/g
As you can probably see I also want to ignore escaped quotes.
Say I have the string "hello? \"world?\""
. This will return 1 which is correct.
But as for this "hello? \"world??\""
. This will also return 1, but what I want is 2. How can I accomplish this?
Also extra love if I can get a regex that is the exact opposite of this (counting question marks that are NOT in quotes).
Here's the whole function used for this test if it helps.
function countTest(str) {
regx = /(\"|\')(([^\"\'\\]|\\.)*)\?(([^\"\'\\]|\\.)*(\"|\'))/g;
test = str.match(regx);
test = test ? test.length : 0;
console.log(test);
}
EDIT:
Also! I noticed from my own typo in this question the string hello \"world?\'"
will also return 1. That seems easy to fix though.
So I just tried it, and apparently the reason the 1 is displayed is, because test is treated not as a String, but as an array. So I would replace
test = test ? test.length : 0;
by
test = test ? new String(test).length - 3 * test.length + 1: 0;
In other words, you are subtracting the 3 characters "," from the String value of the array, but add the 1 because there is no comma character for the first array element.
Edit: For the counting question marks outside quotes, just simply subtract the number given above from the number of total question marks in the string.
Edit: for PHP, you would probably use the array_slice function instead of new String(test), with the multiplication and addition constants adjusted as necessary.