简体   繁体   English

用javascript编写正则表达式的最佳方法是什么?

[英]What is the best way to write a regular expression in javascript?

Good day! 美好的一天!

I don't know regular expressions very well, but I tried to compose one. 我对正则表达式不太了解,但我尝试编写一个正则表达式。 I need this regular expression matched a record for example: 我需要这个正则表达式匹配一条记录,例如:

The user enters any value in the text field that can start with 00x00 and end with 12x99 , it must contain only the sign "x" and the first pair of numbers (the one before "x") must not exceed the number "12" . 用户输入在文本字段可与启动的任何值00x00和结尾12x99 ,它必须包含唯一的符号"x"和第一对数(前“X”的)必须不超过数"12"

I tried a record like this: 我尝试过这样的记录:

/^(00|01|02|03|04|05|06|07|08|09|10|11|12)x([0-9]{2,2})&/

and it fits me, but it's too long expression, I'm sure there's something shorter. 它很适合我,但是它的表达时间太长,我敢肯定还有一些简短的内容。 Asking for help from You ! 向您寻求帮助!

You can shorten the expression quite a bit. 您可以将表达式缩短很多。

^(0\d|1[0-2])x\d{2}$

First you can remove the parenthesis around the entire expression, they are not required if you want a full match. 首先,您可以删除整个表达式周围的括号,如果要完全匹配,则不需要。

The you can replace every [0-9] block with the \\d token. 您可以用\\d令牌替换每个[0-9]块。

Then the quantifier can be simplified if you want a strict quantity {2,2} to {2} 然后,如果您想要从{2,2}{2}的严格数量,则可以简化量词

The first part is a bit more tricky. 第一部分比较棘手。 You can actually separate the match in 2 parts. 您实际上可以将比赛分为两部分。 You need to match every number from 00 to 09 , and every number from 10 to 12 . 您需要匹配从0009每个数字,以及从1012每个数字。

So this is exactly what we are going to do. 所以这正是我们要做的。

First the match from 00 to 09 , the first digit doesn't change, so that's easy. 首先是从0009的匹配,第一位数字不变,所以很容易。 The second digit is a full range from 0 to 9, so we use \\d as previously mentioned. 第二个数字是从0到9的完整范围,因此我们使用\\d如前所述。 That gives us 0\\d . 得出0\\d

The second half has the same fixed first digit, 1. Again that's easy. 后半部分的第一个数字固定不变,即1.。同样,这很容易。 Then it's actually a shortened range from 0 to 2. That gives us 1[0-2] . 然后实际上是从0到2的缩短范围。这给了我们1[0-2]

Could be one or the other, so we encapsulate that part and use the | 可以是另一个,所以我们封装了该部分并使用| (or) token. (或)令牌。

And that's it, we combine everything and get the expression above! 就是这样,我们将所有内容组合在一起并获得上面的表达式!

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

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