简体   繁体   English

正则表达式 - 匹配没有前导和尾随空格的字符串

[英]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 ]*(?<! )$

Live demo 现场演示

But if the environment doesn't support lookarounds the following regex works in most engines: 但是如果环境不支持外观,则以下正则表达式适用于大多数引擎:

^[A-Za-z0-9]+(?: +[A-Za-z0-9]+)*$

depending on your regex engine supporting look around 取决于你的正则表达式引擎支持环顾四周

^(?=[A-Za-z0-9])([A-Za-z0-9\s]*)(?<=[A-Za-z0-9])$

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式将键/值与空格分隔符匹配,没有前导/尾随空格,AND 值可以有空格 - Regex to match key/value with whitespace delimiter, without leading/trailing whitespace, AND value can have spaces 正则表达式与 javascript 中 email 地址的前导和尾随空格不匹配 - Regex to not match leading and trailing white spaces for email address in javascript 正则表达式将匹配6个字符,只允许数字,前导和尾随空格 - Regex that will match 6 characters that only allows digits, leading, and trailing spaces 正则表达式从字符串中删除前导和尾随特殊字符和空格 - Regex to remove leading and trailing special characters and spaces from string Powershell正则表达式匹配前导和尾随空格 - Powershell Regex matches leading and trailing spaces Java正则表达式使用空格去除前导和尾随零 - Java Regex to Strip Leading & Trailing Zeros with Spaces 正则表达式电子邮件 - 忽略前导和尾随空格? - Regex Email - Ignore leading and trailing spaces? 在此JavaScript RegEx中添加删除前导和尾随空格 - Adding removing leading and trailing spaces in this JavaScript RegEx REGEX 删除 ( ) 内的前导和尾随空格 - REGEX drop leading and trailing spaces within ( ) 正则表达式匹配除逗号(包括逗号)前后的空格以外的所有空格 - Regex Match All Except Leading and Trailing Spaces Around Commas (including comma)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM