# 使用正则表达式检查字符串长度

Regular expressions are the ace up the sleeve of many of the most talented programmers out there. With a solid understanding of how regular expressions work, it’s sometimes possible to bypass a tangled mess of conditional logic and recursive function calls with a simple one-liner that just gets the job done much more efficiently.

One of the convenient places to use regular expressions is when doing form validation. With HTML5 it’s possible to enforce attributes like field length, but if someone tries to mess with your security and post values without using the form, you need to be able to verify that what you intended and what you’re getting are consistent.

To check the length of a string, a simple approach is to test against a regular expression that starts at the very beginning with a ^ and includes every character until the end by finishing with a $. You specify the number of characters you want to accept by putting that value inside curly braces right before the ‘$’ at the end.

## 确切长度 (Exact Length)

For example, if I wanted a regular expression that had to consist of exactly seven letters, I might write a regular expression like this:

/^[a-zA-Z]{7}$/ This will match a seven-letter string like ‘abcdefg’ but not any string longer or shorter than seven letters, and certainly not any string containing anything else but letters. 这将匹配七个字母的字符串，例如“ abcdefg”，但不会匹配任何长于或短于七个字母的字符串，当然也不会匹配除字母以外的任何其他字符串。 ## 长度范围 (Length Range) It might be more sensible for real users if I also included a lower limit on the number of letters. To do this, just add a lower value and a comma before the upper limit inside the curly braces: 如果我还对字母的数量设置了下限，则对实际用户可能更明智。 为此，只需在花括号内的上限之前添加一个较低的值和一个逗号： /^[a-zA-Z]{3,7}$/

Now any set of letters between three and seven letters will be matched.

## 最小长度 (Minimum Length)

If, on the other hand, I just wanted to set the lower limit, I could leave off the second value, as long as I included the comma:

/^[a-zA-Z]{3,}\$/

Now a string of at least three letters, but extending to any length, and containing nothing other than letters, will be matched. Depending on your language, that could be a complicated proposition to test for without the convenience of regular expressions.

Learn how to use regular expressions in your coding, and you will start discovering a wide range of useful applications. They may look cryptic at first, but becoming adept with regular expressions will pay off in the long run.

06-01 3037
03-18 1万+
07-20 6331
07-12 7万+
04-03 997
07-27 323
02-22 206
05-13 4787

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助