如果它是字符串的最后一个字符或下一组不匹配,请不要匹配空格?(Do not match white space if it is the last character of the string or

编程入门 行业动态 更新时间:2024-10-13 20:19:30
如果它是字符串的最后一个字符或下一组不匹配,请不要匹配空格?(Do not match white space if it is the last character of the string or the next group does not match?)

我有一个用于识别牙齿的正则表达式,正则表达式如下:

/((U|L)(R|L)[0-8a-eA-E](\s|\/|-|_)?((M|O|D|I|B|P|L)+)?)/gi

它应该(并且确实)匹配以下内容:

UR7

UR7 MOD

UR5-MOD

问题是,最后一部分(在UR和数字之后)是可选的,因此可能是它们没有输入,这很好但是遗憾的是可选空间仍然匹配,例如:

UR7

(请注意UR7之后的空间)以及空间。

我可以看到两种方法来解决这个问题:

如果下一组匹配,只匹配该组(\ s | / | - | _)? 要么 如果它是匹配的最后一个字符,则不匹配组(\ s | / | - | _)。

谁能帮助我实现这个目标?

所以上述匹配所需的行为是匹配的,但对于带有空格的UR7,只匹配UR7而不是空格!

非常感谢!

I have a Regex that is used to recognise tooth, The regex is as follow:

/((U|L)(R|L)[0-8a-eA-E](\s|\/|-|_)?((M|O|D|I|B|P|L)+)?)/gi

It should (and does) match the following:

UR7

UR7 MOD

UR5-MOD

The problem is, The last part (after the UR and the number) are optional so it could be that they are not entered, which is fine however unfortunately the optional space is still being matched so for example:

UR7

(Please notice the space after the UR7) matches the space as well ..

I can see two ways to tackle this:

Only match this group (\s|/|-|_) if the next group matches? or Do not match the group (\s|/|-|_) if it is the last character of a match.

Could anyone please help me to achieve this?

So the desired behaviour is for all the above matches to match but for a UR7 with a space after to match only the UR7 and not the space!

Thank you so much!

最满意答案

仅当分隔符后跟更多内容时,才将分隔符标记为可以容忍。

我还重构了为单个字符使用字符类,因为这通常更有效。

/[UL][RL][0-8a-eA-E]((\s|[-\/_])?[MODIBPL]+)?/gi

Mark the separator as tolerated only when it is followed by something more.

I have also refactored to use character classes for single characters, as that is typically more efficient.

/[UL][RL][0-8a-eA-E]((\s|[-\/_])?[MODIBPL]+)?/gi

更多推荐

本文发布于:2023-07-14 18:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1106689.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:它是   请不要   空格   字符串   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!