函数不会将括号转换为负号

时间:2020-08-19 10:35:16

标签: javascript regex

import React from "react";
import "./styles.css";
import numeral from "numeral";

const value_regex = /(-?\d+,?\.?(\d+)?)+/;
const format_dec = "0.00";

const formatIssue = (value, format = "0,0.00") => {
  if (value) {
    try {
      return numeral(value).format(format);
    } catch (e) {
      return value;
    }
  }
  return value;
};

function onValueChange(evt) {
  if (evt.target.value) {
    try {
      const numericValue = evt.target.value.match(value_regex)[0];

      console.log("value", formatIssue(numericValue, format_dec));
      return formatIssue(numericValue, format_dec);
    } catch (e) {
      return evt.target.value;
    }
  } else {
    return evt.target.value;
  }
}

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <form>
        <label>
          <input type="text" name="name" onBlur={onValueChange} />
        </label>
      </form>
    </div>
  );
}
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我试图允许输入显示正则表达式匹配的值,但是如果值($ 200.00)不这样做。如果值的值是($ 200.00),则其格式应为-200.00。 问题是,是否有可能在不更改'value_regex'的情况下做到这一点

(-?\d+,?\.?(\d+)?)+

https://regex101.com/r/l3gc3N/1

我的代码是: https://codesandbox.io/s/inspiring-moon-1dz6n?file=/src/App.js:88-99

1 个答案:

答案 0 :(得分:0)

尽管您写道您不希望更改正则表达式,但我确实认为需要进行更改。

当然,它不应该削弱其当前的任何功能,并且可以通过使用管道(|)后接替代模式来实现。

因此,如果我们不触摸正则表达式中已经存在的内容,它将扩展为:

const value_regex = /(-?\d+,?\.?(\d+)?)+|\(\$?(\d+,?\.?(\d+)?)+\)/;

尽管我真的很想更改您的当前正则表达式-但我将其留给您-这样它就会变成:

const value_regex = /-?\d+[,.]?\d*|\(\$?\d+[,.]?\d*\)/;

...因为:

  • (\d+)?确实是\d*,但没有捕获组(您没有任何引用)。
  • 我怀疑使用,?\.?时,您实际上是想说小数点分隔符可以是 或点,而实际上也可以允许,.。因此,我将其替换为[,.]?
  • 外部()+允许数字中包含多个-,以及尽可能多的十进制分隔符,这实际上并不是我们写数字的方式。

使用这些方法之一,您只需要将此行添加到代码中即可:

if (numericValue[0] === "(") numericValue = "-" + numericValue.slice(1);

如果您的正则表达式也在其他上下文中使用,则只需将此value_regex设置为事件处理程序中的局部变量即可。这样,它将不会影响任何其他依赖项。