[英]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". 上面的字符串将被数学格式化或读为“ x --3幂的100倍,再加上x的两倍,减去十”。
And I want to match the "+" before "2x" and the "-" before the "10" but not the "-" after "100x^". 我想匹配“ 2x”之前的“ +”和“ 10”之前的“-”,而不是 “ 100x ^”之后的“-”。 I hope it's not that confusing.
我希望那不是那么令人困惑。 I have tried the following reg, with no luck:
我尝试了以下reg,但没有运气:
[^\^][\+|\-]
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. 我将
@
用作临时字符(但是您可以使用一组独特的字符)来标记没有以^
为前缀的符号,然后用所选的临时字符安全地分开。
试一下:
/(?<!\^)[+-]/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.