How can I validate with regex that a question was asked?

1

How can I validate with regex that a question was asked? Is it possible? example:

var text = "¿cómo estas hoy? pareces cansado"
text.match(/([¿?]).*/)
    
asked by Alexander Enrique Toscano Rica 01.09.2018 в 15:11
source

3 answers

3

I would consider that there may or may not be ¿ but if there is ? there must be at least one character before, ?cómo estas hoy pareces cansado does not look like much to a question. Here are some examples:

    var text = "¿cómo estas hoy? pareces cansado"//true
    var text2 = "cómo estas hoy? pareces cansado"//true
    var text3 = "cómo estas hoy pareces cansado"//false
    var text4 = "¿cómo estas hoy pareces cansado"//false
    var text5 = "?cómo estas hoy pareces cansado"//false 

    console.log(/¿?.+\?/g.test(text))
    console.log(/¿?.+\?/g.test(text2))
    console.log(/¿?.+\?/g.test(text3))
    console.log(/¿?.+\?/g.test(text4))
    console.log(/¿?.+\?/g.test(text5))

Either way, there are many aspects that we are probably not considering, such as what happens if there are other punctuation marks ... .?cómo estas hoy pareces cansado or spaces ..

    
answered by 02.09.2018 в 02:22
1

Some use "¿" others do not. I think I search if the text string has "?" it is enough. In regex you have to use the backslash (\) to escape the meta character "?".

It is not necessary to use modifiers of the regex since if you find it only once, it is a question.

let str = "¿cómo estas hoy? pareces cansado";
let rex = /\?/gi;
let esPregunta = (str.search(rex) > -1) ? true : false ;
console.log(esPregunta);// si es pregunta devuelve true.

I hope my answer is useful.

    
answered by 01.09.2018 в 17:59
1
  

note: Written this here because it is too long for a   comment

The question is complicated, since regular expressions only understand certain simple rules and not natural languages.

You should define what you consider a question so that you can respond as accurately as possible.

For example:

  • Should the questions begin with ¿ ?
  • Questions of one or few words such as: ¿tú? , ¿quién? , ¿12.000?
  • Or, on the contrary, the questions should be more elaborate. In that case, would it be enough to look for a minimum number of words? For example: at least 3 words: ¿Cómo te llamas? If so, how many?

Anyway, remember that even with the best definition of rules and the best execution in the form of regular expression, you will always have cases not detected and false positives.

Furthermore, it is also not clear if you try to look for different questions within a larger block of text. Or on the contrary it is understood that you already have separate the 'phrases', and you simply want to evaluate if any of these phrases is a question.

    
answered by 04.09.2018 в 16:36