There is a regular expression:

^[а-яё?\s]+$ 

How to supplement this regular season so that spaces are cut off at the beginning and at the end, and inside the word space is allowed? Ie "Ivan Ivanov" - skip, "Ivan Ivanov" - do not miss?

  • 6
    Why not use trim() ? Give an example of code that does not work for you. - Wiktor Stribiżew
  • one
    It seems you need to decompose the character class into groups / "atoms", try /^[а-яё?]+(?:\s[а-яё?]+)*$/i - Wiktor Stribiżew
  • Ie "Ivan Ivanov" - skip, "Ivan Ivanov" - do not miss? - the current regexp seems to be exactly the way it works - Grundy
  • @Grundy, Space at the end of the line and at the beginning of the match. - V.Manokhin
  • @Wiktor Stribiżew, your regular season fits, thanks - V.Manokhin

4 answers 4

I propose to parse the character class into spaces and everything else and add the following expression:

 /^[а-яё?]+(?:\s+[а-яё?]+)*$/i 

or (if only 1 space between words is allowed):

 /^[а-яё?]+(?:\s[а-яё?]+)*$/i 

See the demo .

It will find:

  • ^ - beginning of line
  • [а-яё?]+ - 1 or more Russian letters
  • (?:\s[а-яё?]+)* - 0 or more:
    • \s+ - 1 or more spaces (remove + if only 1 space is allowed between words)
    • [а-яё?]+ - 1 or more Russian letters
  • $ - end of line

    Use .trim (); The original line does not change. Supported everywhere.

     var str = " temp "; str.trim(); 

    Is there some more:

     jQuery.trim(); 

      Here it is possible:

       ^(?:[^ ][а-яё?\s]+[^ ]?|[^ ]?[а-яё?\s]+[^ ])$ 
      • At the end of the line the gap is matched - V.Manokhin

      If you answer the question, then

       ^[^\s][а-яё?\s]*[^\s]$ 

      But it may be better to call trim() ?

      • [а-яё?\s]+? - this is a mistake, in my opinion - Yuri
      • @Yuri: No, not an error ( +? - this is a lazy quantifier + ), but since you also require at least 2 characters in the string. - Wiktor Stribiżew
      • @ WiktorStribiżew At the expense of two characters, you are right. Corrected. - Anton Shchyrov
      • Oh, actually 3 characters per line were required. Now you must have 2 characters. [^\s] requires a symbol. But this, I think, is not so relevant. By the way, the lazy quantifier is out of place here, it only slows down the engine. - Wiktor Stribiżew
      • one
        @ V.Manokhin, the regular line from this answer will completely miss such a line <> . Test regex101.com/r/b7OZfd/1 - Visman