我有一个用于切除字符串
的第一个整数部分的正则表达式(^[0-9]+)|(^\-[0-9]+)
即。使用'12x'
,切片会返回'12'
。我想扩展它,以便在字符串中有'^'
时失败。我尝试使用否定前瞻
(?!\^)(^[0-9]+)|(^\-[0-9]+)
但这不起作用,因为它仍然匹配,例如'12^x'
。我也在'\'
之前没有'^'
的情况下尝试了它,但它没有匹配。我哪里错了?
答案 0 :(得分:2)
这是你目前的负面预测:
(?!\^)
这一前瞻的问题在于它使用了错误的模式来实现您想要的效果。它只向前看一个字符,这意味着它无法检查整个字符串,直到结束存在或不存在克拉。
^(?!.*\^)-?[0-9]+$
<强>解释强>
^(?!.*\^) from the start of the string, look ahead and assert that no carat appears
-?[0-9]+$ match an optional minus sign, followed by any number of digits
在这里演示: