简体   繁体   中英

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. 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). You wanted just the literal four-character string "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.
  • 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.
  • [s|S|f|F] means "s or | or S or |..." You meant "s or S or f...", which is written [sSfF].
  • Since \\i is used to make a search case insensitive, I simplified [sSfF] to [sf]

The [bscs] needs to not be in square brackets: square brackets means b or s or c or s . It works without the number because it matches "l1s10b", but the next character is not a digit so looking for 4 digits fails. 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' OR '|' OR 'S' OR 'f' OR 'F' . That should be (s|S|f|F) or [sSfF] .

NOTE: You can use the i modifier to make it case-insensitive.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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