[英]Regex - match a string without leading and trailing spaces
Building an expression that will reject an untrimmed input string. 构建一个拒绝未修剪的输入字符串的表达式。
Have a group of white-listed symbols, including whitespace . 有一组列入白名单的符号,包括空格 。 But it cannot be used at the first or at the last one position. 但它不能在第一个或最后一个位置使用。 However, it may be used between any leading and trimming white-listed symbol in any amount. 但是,它可以在任何数量的任何前导和修剪白名单之间使用。
Have a following expression: 有以下表达式:
^[^\s][A-Za-z0-9\s]*[^\s]$
... but it doesn't work in several reasons, at least it still matches at leading and trailing position any non-whitespace symbol even if it's not white-listed. ...但它有多种原因无效,至少它仍然在前导位置和尾随位置匹配任何非空白符号,即使它不是白名单。 Futhermore, it won't match single letter word even if it matches to the expression. 此外,即使它与表达式匹配,也不会匹配单个字母单词。
The whitelist is AZ, az, 0-9, whitespace. 白名单是AZ,az,0-9,空格。
Valid case: 有效案例:
Abc132 3sdfas // everything ok
Invalid case #1: 案例#1无效:
asd dsadas // leading\trailing space is exist
Invalid case #2: 案例#2无效:
$das dsfds // not whitelisted symbol at the leading\trailing position
So, how to add a whitespace symbol to the white-list if it isn't the leading or the trailing symbol? 那么,如果它不是前导符号或尾随符号,如何在白名单中添加空白符号?
You could use lookarounds to ensure that there are no spaces at both ends: 您可以使用lookarounds来确保两端都没有空格:
^(?! )[A-Za-z0-9 ]*(?<! )$
But if the environment doesn't support lookarounds the following regex works in most engines: 但是如果环境不支持外观,则以下正则表达式适用于大多数引擎:
^[A-Za-z0-9]+(?: +[A-Za-z0-9]+)*$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.