简体   繁体   English

如何匹配除指定字符和字符串之外的所有内容? 正则表达式

[英]How to match everything except specified characters and strings? Regex

I am building a graph drawer and currently working on the math expression parser. 我正在构建一个图形抽屉,目前正在使用数学表达式解析器。 I'm done with most parts but I'm stuck at clearing the input text before parsing it. 我已经完成了大部分工作,但是在解析输入文本之前我一直坚持清除输入文本。 What I'm trying to achieve now is getting rid of unpermitted characters. 我现在想要实现的是摆脱不被允许的字符。

For example, in this text: 例如,在此文本中:

5ax+4asxxv+sdflog10aloga(132*43)sin(132) 5ax + 4asxxv + sdflog10aloga(132 * 43)sin(132)

I want to match everything that is not + , - , * , / , ^ , ( , ) , ln , log , sin , cos , tan , cot , arcsin , arccos ,... and replace them with "" . 我想匹配不是+-*/ ^( )lnlogsincostancotarcsinarccos ,...等所有内容,并将其替换为""

so that the output is 这样的输出是

5x+4xx+log10log(132*43)sin(132) 5x + 4xx + log10log(132 * 43)sin(132)

I need help with the regex. 我需要有关正则表达式的帮助。

Spaces don't matter since I clear them out beforehand. 空间无所谓,因为我事先已将其清除。

A little bit tricky - at least I couldn't think of a simple way to do what you ask. 有点棘手-至少我想不出一种简单的方法来完成您的要求。 The regex would get monstrous. 正则表达式会变得可怕。

So I did it the other way around - match what you want to keep, and put it back together. 所以我反过来做了-匹配您想要保留的内容,然后放回原处。

The regex: 正则表达式:

[\d+*/^()x-]|ln|log|(?:arc)?(?:sin|cos)|tan|cot

The code: 编码:

 var re = /[\\d+*/^()x-]|ln|log|(?:arc)?(?:sin|cos)|tan|cot/g, text = '5ax+4asxxv+sdflog10aloga(132*43)sin(132)arccos(1)'; console.log(text.match(re).join('')); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM