如何形成正则表达式以识别变量名的正确声明 [英] How to form a regex to recognize correct declaration of variable names

查看:71
本文介绍了如何形成正则表达式以识别变量名的正确声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想组成一个正则表达式ro来识别变量名的声明.用户将输入他们想要的字符串作为变量名,程序必须检查该变量是否有效.

I would like to form a regex ro recognize the declaration of a variable name. User will enter a string that they would like as a variable name, and the program has to check whether the variable is valid.

  1. 变量名称的第一个字符必须是字母或下划线.它不能以数字开头.
  2. 变量名中不允许使用逗号和空格.
  3. 变量名中除下划线外不允许使用其他特殊符号.

我整天都在尝试,但没有得到正确的答案.

I have been trying for the whole day and couldn't get the correct one.

推荐答案

我们要做的第一件事是收集第一个字符的所有有效字符的列表:

First thing we do is gather a list of all the valid characters for the first character:

[a-zA-Z_$]

然后是其他字符:

[a-zA-Z_$0-9]

我们要匹配整个字符串,并且可以有0个或多个其他字符,因此正则表达式变为:

we want to match the whole string, and we can have 0 or more of the other characters, so the regex becomes:

^[a-zA-Z_$][a-zA-Z_$0-9]*$

我允许在正则表达式的第一个字符(以及美元符号)中使用大写字母,因为这是对有效性的测试,而不是对格式正确的变量的测试.(请注意,常量应该大写,包括首字母.)

I allow capital characters in the first character in the regex (as well as dollar signs), because this is a test for validity, not for well-formed variables. (Note that constants should be in all caps, including the first letter.)

这篇关于如何形成正则表达式以识别变量名的正确声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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