本文介绍了Javascript条件正则表达式if-then-else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将条目限制为特定格式。

I'm trying to limit the entries to a specific format.

如果条目有5500或5100,例如01\01-5500-000-00然后我想要这个:

If the entry has 5500 or 5100 such as 01\01-5500-000-00 then I want to have this:

^[0-9]{2,}\\[0-9]{2}\-[0-9]{4}\-[0-9]{3}\-$

但是如果条目中有5500或5100以外的任何东西我想要这个:

But if the entry has anything other than 5500 or 5100 I want to have this:

^[0-9]{2,}\\[0-9]{2}\-[0-9]{4}\-[0-9]{3}\-[0-9]{2}$

如何通过if then else理念实现这一目标?

How can this be accomplished with the if then else idea?

推荐答案

JavaScript正则表达式引擎不支持条件正则表达式语法,但它可以解决包含2个备选方案的非捕获组:

Conditional regex syntax is not supported by JavaScript regex engine, but it can be worked around with a non-capturing group containing 2 alternatives:


  1. 一个有正向前瞻和

  1. One with the positive look-ahead and

第二个是反向,负向前瞻。

The second with the reversed, negative look-ahead.

此正则表达式符合您的标准并且是JavaScript兼容的le:

This regex meets your criteria and is JavaScript compatible:

^(?:(?=.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}-|(?!.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2})$

参见

让我分解:


  • ^ - 字符串开头

  • (?:


    • (?=。* \ b5 [15] 00 \ b)[0-9] {2, } \\ [0-9] {2} - [0-9] {4} - [0-9] {3} - - 的第一个替代方案(?=。* \ b5 [15] 00 \ b)预测需要一个完整的单词 5500 5100 字符串内,第一个模式是

    • | - 交替运营商

    • (?!。* \ b5 [15] 00\b)[0-9] {2,} \ \ [0-9] {2} - [0-9] {4} - [0-9] {3} - [0-9] {2}) - 第二个替代方案是前缀为(?!。* \ b5 [15] 00 \b)负面预测,确保没有 5100 5500 在字符串内,然后才匹配你的第二个模式。

    • ^ - Start of string
    • (?:
      • (?=.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}- - First alternative with the (?=.*\b5[15]00\b) look-ahead that requires a whole word 5500 or 5100 inside the string, and the first pattern you have
      • | - alternation operator
      • (?!.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2}) - Second alternative that is prepended with the (?!.*\b5[15]00\b) negative look-ahead that makes sure there is no 5100 or 5500 inside the string, and only then matches your second pattern.

      这篇关于Javascript条件正则表达式if-then-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 22:49