Regular expression to ban two consecutive spaces in the middle of a line

I need a regular expression to satisfy the following requirements:

  • Only letters, periods and spaces are allowed.
  • There is no space at the beginning and end of the line.
  • The white space in the middle of the line is fine, but not two white spaces in a row.

Matches:

"Hello world."
"Hello World. This is ok."

Does not match:

" Hello World. "
"Hello world 123." 
"Hello  world."

This worked in my case.

<asp:RegularExpressionValidator ID="revDescription" runat="server" 
                                ControlToValidate="taDescription" Display="Dynamic" ErrorMessage="Invalid Description." 
                                Text="&nbsp" 
                                ValidationExpression="^(?i)(?![ ])(?!.*[ ]{2})(?!.*[ ]$)[A-Z. ]{8,20}$"></asp:RegularExpressionValidator>
+4
source share
2 answers

Here's the solution in Python, using anchors and negative lookahead statements to make sure that the rules for spaces are followed:

regex = re.compile(
    """^          # Start of string
    (?![ ])       # Assert no space at the start
    (?!.*[ ]{2})  # Assert no two spaces in the middle
    (?!.*[ ]$)    # Assert no space at the end
    [A-Z. ]{8,20} # Match 8-20 ASCII letters, dots or spaces
    $             # End of string""", 
    re.IGNORECASE | re.VERBOSE)
+2
source

, .

JavaScript:

if (str.length < 8 || str.length > 20)
  return false;
if (str.match(/(^\s|\s$|\s\s|[^A-Za-z.\s])/))
  return false;

:

  • ^\s
  • \s$
  • \s\s
  • [^A-Za-z.\s] , , .

(ASCII 32), , \s .

"" "", :

return str.match(/[A-Za-z. ]){8,20}/) && !str.match(/(^ | $|  )/);

. , , , -, . , , , 6 18 , :

[A-Z][A-Z. ]{6,18}[A-Z]
0

All Articles