正则表达式条件不适用于聚合物纸输入,如何在纸输入上只允许小数?

regex condition not working on polymer paper-input, how to allow only decimal on paper input?

我试图在纸张输入中只允许小数。以下是我的条件。

不应允许 e 应该允许 +, - 例如:-23.43 点后应仅允许 12 个值(十进制),例如:107.123456789012

所以我尝试了下面的正则表达式,但都不起作用。

   ^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d{1,12})?$
    /^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/

        <paper-input allowed-pattern="^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$">
        </paper-input>

上面的正则表达式只接受整数,不接受小数。所以尝试了下面的一个。它工作正常。但不确定如何限制小数。我只想在 DOT(decimal)

之后允许 12 个值
<paper-input  allowed-pattern="[-.\d]"> </paper-input>

你可以用这个

^[+-]?\d+\.\d{1,12}$

Explanation

  • ^ - 字符串开头的锚点。
  • [+-]?\d+ - 匹配 +-(两者都是可选的)一个或多个数字。
  • \. - 匹配 ..
  • \d{1,12} - 匹配 1 到 12 个数字。

Demo

const regex = /^\d+\.\d{1,12}$/gm;
const str = `1.1
0
1.123456789123
a1223
0000.1111
1.abv
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

From the doc:

pattern 用于验证输入值的正则表达式模式

<paper-input pattern="[A-Z]{2}[0-9]{6}"></paper-input>

/**
* For this input “EN123456” is a valid value, 
* but "EN123456 " or " EN123456" are invalid values
* because there are extra characters 
* and value doesn't match a pattern
*/

allowed-pattern — 限制允许输入的字符的模式

// accepts letters only
<paper-input allowed-pattern="[a-zA-Z]"></paper-input>

// accepts digits only
<paper-input allowed-pattern="[0-9]"></paper-input>

// accepts nothing, because one character cannot match this pattern
<paper-input allowed-pattern="[0-9][A-Z]"></paper-input>

应该使用:

<paper-input pattern="^(?!-0(?:\.0+)?$)-?(?:0|[1-9]\d*)(?:\.\d+)?$">

我也把capture grops改成了non-capture groups,效率更高