Reactjs can´;t使Regex在React计算器中工作
我一直试图让这个正则表达式在我的React计算器中用于格式输入(它应该将操作和运算符限制为有效的数学格式。例如,不允许使用1+++++1,应将其替换为1+1,12*+-3应替换为12-3,等等)。正则表达式如下:/^\d*([/+-/=]\d+$/gi)。 不管我怎么努力,我都不能让它工作。我一直收到一个“转义序列”错误 计算器:Reactjs can´;t使Regex在React计算器中工作,reactjs,Reactjs,我一直试图让这个正则表达式在我的React计算器中用于格式输入(它应该将操作和运算符限制为有效的数学格式。例如,不允许使用1+++++1,应将其替换为1+1,12*+-3应替换为12-3,等等)。正则表达式如下:/^\d*([/+-/=]\d+$/gi)。 不管我怎么努力,我都不能让它工作。我一直收到一个“转义序列”错误 计算器: class Calculator extends Component { constructor(props) { super(props); t
class Calculator extends Component {
constructor(props) {
super(props);
this.state = {value:""}
this.handleClick = this.handleClick.bind(this);
}
handleClick(evt){
const id=evt.target.id;
const result= evt.target.value;
this.setState(prevState => ({
value: `${prevState.value}${result}`.replace(/^0+\B/, "")
}));
if(id==="equals"){
this.setState({value: math.eval(this.state.value)})
}
else if(id==="clear"){
this.setState({value : 0})
}
}
render() {
return(
<div id="container">
<Display value={this.state.value} />
<Button onClick={this.handleClick} id="zero" value={'0'} />
<Button onClick={this.handleClick} id="one" value={'1'} />
<Button onClick={this.handleClick} id="two" value={'2'}/>
<Button onClick={this.handleClick} id="three" value={'3'} />
<Button onClick={this.handleClick} id="four" value={'4'} />
<Button onClick={this.handleClick} id="five" value={'5'} />
<Button onClick={this.handleClick} id="six" value={'6'} />
<Button onClick={this.handleClick} id="seven" value={'7'} />
<Button onClick={this.handleClick} id="eight" value={'8'} />
<Button onClick={this.handleClick} id="nine" value={'9'} />
<Button onClick={this.handleClick} id="decimal" value={'.'} />
<Button onClick={this.handleClick} id="equals" value={'='} />
<Button onClick={this.handleClick} id="clear" value={'clear'} />
<Button onClick={this.handleClick} id="add" value={'+'} />
<Button onClick={this.handleClick} id="subtract" value={'-'} />
<Button onClick={this.handleClick} id="multiply" value={'*'} />
<Button onClick={this.handleClick} id="divide" value={'/'} />
</div>
)
}
类计算器扩展组件{
建造师(道具){
超级(道具);
this.state={value:}
this.handleClick=this.handleClick.bind(this);
}
handleClick(evt){
const id=evt.target.id;
const result=evt.target.value;
this.setState(prevState=>({
值:`${prevState.value}${result}`。替换(/^0+\B/,“”)
}));
如果(id==“等于”){
this.setState({value:math.eval(this.state.value)})
}
否则如果(id==“清除”){
this.setState({value:0})
}
}
render(){
返回(
)
}
展示
const Display = (props) => {
return (
<div>
<h2 id="display">{props.value} </h2>
</div>
)};
const Display=(道具)=>{
返回(
{props.value}
)};
钮扣
const Button = (props) => {
return (
<input type="button" onClick={props.onClick} id={props.id} value={props.value} />
)
};
const按钮=(道具)=>{
返回(
)
};
您的逻辑似乎是,如果连续有多个运算符,您希望删除所有运算符符号并仅保留最后一个。我们可以尝试在以下正则表达式模式中查找:
(?:[+/*-])*([+/*-])
然后替换为最后捕获的符号
input1=“1+++++1”;
input2=“12*+-3”;
input1=input1.replace(/(?:[+/*-])*([+/*-])/g,“$1”);
控制台日志(输入1);
input2=input2.replace(/(?:[+/*-])*([+/*-])/g,“$1”);
console.log(输入2);