简体   繁体   English

无法使用javascript制作正则表达式

[英]unable to make a regular expression using javascript

I want to make a regular expression for my university registration number. 我想为我的大学注册号码做一个正则表达式。 I am 75% successful to make it. 我成功率75%。 I'm new and i don't know how to make it. 我是新人,我不知道该怎么做。 This is what i am doing. 这就是我在做的事情。

<!DOCTYPE html>
<html> 
<body>

<script>
str = "l1s10bscs"; //successfully tested
                   //but i want to append any 4 digits at the end of l1s10bscs

re = /[a-zA-Z]\d{1}[s|S|f|F]\d{2}[bscs]/g;

result = re.test(str);

document.write(result);

</script>

</body>
</html>

i tried this but it doesn't work. 我试过这个,但它不起作用。

re = /[a-zA-Z]\d{1}[s|S|f|F]\d{2}[bscs][0-9]{4}/g;  // this doesn't work 
/[a-z]\d[sf]\d{2}bscs\d{4}/i

According to your description, this should fit. 根据你的描述,这应该适合。

I changed the following: 我改变了以下内容:

  • [bscs] means "b or s or c or s" (so "b or s or c", the extra s is meaningless). [bscs]表示“b或s或c或s”(所以“b或s或c”,额外s无意义)。 You wanted just the literal four-character string "bscs" 你只想要文字四字符串“bscs”
  • \\d{1} is the same as \\d - this isn't an error, but there's no reason to explicity define a character as occurring only once. \\ d {1}与\\ d相同 - 这不是错误,但没有理由明确将角色定义为仅发生一次。
  • You have a \\g flag but no \\i, so you'll match the string you're looking for multiple times inside of a larger string, but your search isn't case insensitive. 你有一个\\ g标志,但没有\\ i,所以你将匹配你在一个更大的字符串中多次寻找的字符串,但你的搜索不区分大小写。
  • [s|S|f|F] means "s or | or S or |..." You meant "s or S or f...", which is written [sSfF]. [s | S | f | F]表示“s或|或S或| ......”表示“s或S或f ......”,写成[sSfF]。
  • Since \\i is used to make a search case insensitive, I simplified [sSfF] to [sf] 由于\\ i习惯于使搜索大小写不敏感,我将[sSfF]简化为[sf]

The [bscs] needs to not be in square brackets: square brackets means b or s or c or s . [bscs]不需要放在方括号中:方括号表示bscs It works without the number because it matches "l1s10b", but the next character is not a digit so looking for 4 digits fails. 它没有数字,因为它匹配“l1s10b”,但下一个字符不是数字,所以寻找4位数失败。 Try this: 尝试这个:

re = /[a-zA-Z]\d{1}[s|S|f|F]\d{2}bscs[0-9]{4}/g;

You seem to be confusing [] and () . 你似乎混淆了[]()

() creates a group, whereas [] means "match any letter from inside". ()创建一个组,而[]表示“匹配来自内部的任何字母”。

[s|S|f|F] means 's' OR '|' OR 'S' OR 'f' OR 'F' [s|S|f|F]表示's' OR '|' OR 'S' OR 'f' OR 'F' 's' OR '|' OR 'S' OR 'f' OR 'F' . 's' OR '|' OR 'S' OR 'f' OR 'F' That should be (s|S|f|F) or [sSfF] . 那应该是(s|S|f|F)[sSfF]

NOTE: You can use the i modifier to make it case-insensitive. 注意:您可以使用i修饰符使其不区分大小写。

re = /[a-z]\d[sf]\d{2}bscs\d{4}/gi;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM