简体   繁体   中英

Regex match any string that isn't preceded by another string

I suck at regex and I've been trying to get through this problem. The problem is that I have a string and I want to match any "+" or "-" that aren't preceded by a "^".

Example string:

100x^-3+2x-10

The string above would be mathematically formatted or read as "one hundred times x to the -3 power, plus two times x, minus ten".

And I want to match the "+" before "2x" and the "-" before the "10" but not the "-" after "100x^". I hope it's not that confusing. I have tried the following reg, with no luck:

[^\^][\+|\-]

Obviously I'm missing a big detail somewhere.

您可以通过反转字符串,然后与/[\\+\\-](?!=\\^)/进行匹配,来使用模拟回头的古老技巧。

它可以在chrome控制台中正常运行,无论如何您都可以尝试: "100x^-3+2x-10".match(/[^\\^$]([\\-|\\+])/ig) ,我建议您在Google Chrome浏览器的控制台中测试您的正则表达式。

If you need to split by + or - :

"100x^-3+2x-10".replace(/([^^])[-+]/g,'$1@').split('@')
Output: ["100x^-3", "2x", "10"]

I used @ as a temp char (but you can use a unique set of chars) to mark the signs not prefixed by ^ then safely split by the chosen temp char.

试一下:

/(?<!\^)[+-]/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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