正则表达式

正则表达式其实就是在执行搜索时的格式,它由一些字母和数字组合而成。 例如:一个正则表达式 the,它表示一个规则:由字母t开始,接着是h,再接着是e。

正则表达式提供一些常用的字符集简写。如下:

简写 描述
. 除换行符外的所有字符
\w 匹配所有字母数字,等同于 [a-zA-Z0-9_]
\W 匹配所有非字母数字,即符号,等同于: [^\w]
\d 匹配数字: [0-9]
\D 匹配非数字: [^\d]
\s 匹配所有空格字符,等同于: [\t\n\f\r\p{Z}]
\S 匹配所有非空格字符: [^\s]
\f 匹配一个换页符
\n 匹配一个换行符
\r 匹配一个回车符
\t 匹配一个制表符
\v 匹配一个垂直制表符
\p 匹配 CR/LF(等同于 \r\n),用来匹配 DOS 行终止符

您需要检查数据库中的所有用户名。以下是用户在创建用户名时必须遵循的一些简单规则。

  1. 用户名只能使用字母数字字符。
  2. 用户名中唯一的数字必须在末尾。最后可以有零个或多个。用户名不能以数字开头。
  3. 用户名字母可以是小写和大写。
  4. 用户名必须至少有两个字符长。两个字符的用户名只能使用字母作为字符。
测试用例
JACK
J
Jo
Oceans11
RegexGuru
007
9
A1
BadUs3rnam3
Z97
c57bT3
AB1
J%4
let username = "JackOfAllTrades";
let userCheck = /^[a-z]([0-9]{2,}|[a-z]+\d*)$/i; // Change this line
let result = userCheck.test(username);

代码说明

  1. ^ - 开始输入
  2. [a-z] - 第一个字符是一个字母
  3. [0-9]{2,0} - 以两个或更多数字结尾
  4. | - 要么
  5. [a-z]+ - 接下来有一个或多个字母
  6. \d* - 并以零个或多个数字结尾
  7. $ - 输入结束
  8. i - 忽略输入的大小写

第二个正则解决方法

我觉得比较复杂,没有第一个好用

let username = "JackOfAllTrades";
let userCheck = /^[a-z][a-z]+\d*$|^[a-z]\d\d+$/i;
let result = userCheck.test(username);
console.log(result)

代码说明

  1. ^ - 开始输入
  2. [a-z] - 第一个字符是一个字母
  3. [a-z]+ - 以下字符是字母
  4. \d*$ - 输入以 0 个或多个数字结尾
  5. | - 要么
  6. ^[a-z] - 第一个字符是一个字母
  7. \d\d+ - 以下字符为 2 位或更多位数字
  8. $ - 输入结束

2.使用前瞻pwRegex来匹配长度超过 5 个字符且有两个连续数字的密码。

let sampleWord = "astronaut";
let pwRegex = /(?=\w{6,})(?=\w*\d{2,})/; // Change this line
let result = pwRegex.test(sampleWord);

提示

提示 1

记住使用 2lookaheads检查字符串中的模式。第一个lookahead与示例中给出的非常相似 (?=\w{3,6}) 只有lower-number3 对于我们的测试用例来说太低了,而 anupper-number是完全不需要的。这第一个lookahead仅用于查找由一定数量的字符组成的字符串。lookahead必须使用秒来检查字符串末尾的连续数值。

提示 2

第二个lookahead也与示例中给出的相似(?=\D*\d)- 但是,这个表达式也必须修改以通过所有测试用例。请记住指定要出现在字符串末尾的确切数字数量。

3.字符串匹配

Fix the regex so that it checks for the names of Franklin Roosevelt or Eleanor Roosevelt in a case sensitive manner and it should make concessions for middle names.

Then fix the code so that the regex that you have created is checked against myString and either true or false is returned depending on whether the regex matches.

let myString = "Eleanor Roosevelt";
let myRegex = /(Eleanor|Franklin).*Roosevelt/; // Change this line
let result = myRegex.test(myString); // Change this line

4.删除字符串前后的空格

let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g;// Change this line
let result = hello.replace(wsRegex,''); // Change this line