[英]exclude certain characters while matching a regex
/[a-zA-Z]*/
The above matches all characters from az, but I would like to exclude when there is 'if' in the string. 上面的代码匹配了az中的所有字符,但是我想排除字符串中是否包含“ if”。
Tried [^if]
but couldn't accomplish what I was hoping for. 尝试过[^if]
但无法实现我所希望的。
[EDIT] I have a formula evaluator which returns some value: [编辑]我有一个公式评估器,它返回一些值:
value = "if(a < b,a,b+1)"
formula = value.gsub(/[a-zA-Z]*/,'1')
verify = Calc.evaluate(formula)
I am trying to assign 1
to a
and b
inside the string and check if the formula is valid and evaluated. 我正在尝试将1
分配给字符串中的a
和b
并检查该公式是否有效并已评估。
Expected Output: "if(1 < 1,1,1+1)"
You can try this: 您可以尝试以下方法:
/((?!if )[a-zA-Z])*/
string = "abc"
string.match(/((?!if )[a-zA-Z])*/)
# MatchData "abc"
string = "if abc"
# MatchData ""
要得到想要的,可以使用gsub
如下所示:
"if(a < b,a,b+1)".gsub(/[a-zA-Z]+/){|m| m == 'if' ? m : '1' }
I am trying to assign 1 to a and b inside the string... 我正在尝试将1分配给字符串中的a和b ...
Well, if you're trying to do that, then why are you messing with anything but a
or b
? 好吧,如果您要尝试这样做,那么为什么除了a
或b
什么都搞砸了?
str = 'if(a < b,a,b+1)'
str.gsub(/\b[ab]\b/, '1') # => "if(1 < 1,1,1+1)"
\\b
is a word-boundary marker, so \\b[ab]\\b
means a
or b
has to be an individual character. \\b
是单词边界标记,因此\\b[ab]\\b
表示a
或b
必须是单个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.