正则表达式-匹配字符串时不带前导和尾随空格 [英] Regex - match a string without leading and trailing spaces

查看:254
本文介绍了正则表达式-匹配字符串时不带前导和尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构建一个表达式,该表达式将拒绝未修饰的输入字符串.

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.

具有以下表达式:

^[^\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.

白名单是A-Z,a-z,0-9,空白.

The whitelist is A-Z, a-z, 0-9, whitespace.

有效案例:

Abc132 3sdfas // everything ok

无效的情况#1:

 asd dsadas // leading\trailing space is exist

无效的情况#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:

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

这篇关于正则表达式-匹配字符串时不带前导和尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆