如何防止在正则表达式正则表达式验证空白 [英] how to prevent white spaces in a regular expression regex validation

查看:220
本文介绍了如何防止在正则表达式正则表达式验证空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式是全新的,我试图在flex中为正则表达式创建一个正则表达式。



使用正则表达式,我将验证用户输入不包含任何空格,并且只包含字符和数字...以数字开头。



到目前为止我有:

 表达式=[A- Za-z] [A-Za-z0-9] *

正确检查用户输入开始一个字符后面跟一个可能的数字,但是这不检查是否有空白...(在我的测试中,如果用户输入有一个空间,这个输入将通过验证 - 这是不期望的)有人可以告诉我我怎样才能修改这个表达式,以确保用户输入与空白被标记为无效?

解决方案

您需要锚定正则表达式在字符串的开头和结尾:

$ $ $ $ $ $ $ $ $ $表达式=^ [A-Za-z] [A-Za- z0-9] * $

确保不只是一个子字符串,而是整个字符串匹配正则表达式。


I am completely new to regular expressions ,and I am trying to create a regular expression in flex for a validation.

Using a regular expression, I am going to validate that the user input does NOT contain any white-space and consists of only characters and digits... starting with digit.

so far i have:

expression="[A-Za-z][A-Za-z0-9]*"

This correctly checks for user input to start with a character followed by a possible digit, but this does not check if there is white space...(in my tests if user input has a space this input will pass through validation - this is not desired) can someone tell me how I can modify this expression to ensure that user input with whitespace is flagged as invalid?

解决方案

You'll need to anchor the regex at the start and end of the string:

expression="^[A-Za-z][A-Za-z0-9]*$"

makes sure that not just a substring but the entire string is matched by the regex.

这篇关于如何防止在正则表达式正则表达式验证空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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