为正则表达式匹配编写 gsub 的完美方式? [英] Perfect way to write a gsub for a regex match?

查看:52
本文介绍了为正则表达式匹配编写 gsub 的完美方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为正则表达式匹配编写 gsub,但我想有一种更完美的方法可以做到这一点.

I am trying to write a gsub for a regex match, but I imagine there's a more perfect way to do this .

我的方程式:

ref.gsub(ref.match(/settings(.*)/)[1], '')

这样我就可以使用这个settings/animals,然后只返回settings.

So that I can take this settings/animals, and return just settings.

但是如果 settings 为空怎么办?比我的 [1] 按预期失败.

But what if settings is null? Than my [1] fails as expected.

那么假设有时settings 不匹配,如何编写上述语句?

So how can one write the above statement assuming that sometimes settings won't match ?

所以基本上,如果它找到了 settings 这个词,那么它之后的任何东西都会被删除.但如果没有,别担心.

So that basically, if it finds the word, settings, than get rid of anything after it. But if it doesn't, no worries.

谢谢!

推荐答案

为什么不做可能可行的最简单的事情?

Why not do the simplest possible thing that could work?

ref.gsub(/(settings)(.*)/, '\1')

这篇关于为正则表达式匹配编写 gsub 的完美方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆