如何防止正则表达式正则表达式验证中的空格 [英] how to prevent white spaces in a regular expression regex validation
问题描述
我对正则表达式完全陌生,我正在尝试在 flex 中创建一个正则表达式以进行验证.
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.
到目前为止我有:
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屋!