在替换之前处理正则表达式匹配
我正在寻找应用程序和编程语言结构来搜索正则表达式模式,以某种方式转换匹配,然后替换它。一个非常简单的示例:将“myCamelCasedString”转换为“my_camel_cased_string”。
在 Ruby 中,它简单而简洁:
s = "myCamelCasedString".gsub(/[A-Z]/) { |m| "_" + m.downcase }
在 PHP 中,它更长,但也是可能的。
preg_replace_callback('/[A-Z]/',
// Using PHP 5.3 anonymous function as callback
function($m) { return "_" . strtolower($m[0]); },
"myCamelCasedString");
文本编辑器 jEdit 也通过“Beanshell 片段”支持这一点,但我总是必须查找如何做到这一点。那么 - 我将如何在其他语言中执行此操作,是否有专用的应用程序/编辑器可以让我执行此操作(以及可能的转换的方便参考)?
I'm looking for applications and programming language constructs to search for a regular expression pattern, transform the match in some way and then replace it. A very simple example: Transforming "myCamelCasedString" to "my_camel_cased_string".
In Ruby it's easy and concise:
s = "myCamelCasedString".gsub(/[A-Z]/) { |m| "_" + m.downcase }
In PHP it's longer, but also possible
preg_replace_callback('/[A-Z]/',
// Using PHP 5.3 anonymous function as callback
function($m) { return "_" . strtolower($m[0]); },
"myCamelCasedString");
The text editor jEdit also supports this through a "Beanshell snippet" but I always have to look up how to do it. So - how would I do this in other languages and is there a dedicated application/editor that lets me do this (together with a handy reference of possible transformations)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为 Ruby 是您正在寻找的专用应用程序:
数据:
scriptlet:
神奇的酱汁是“-p”开关。它将“-e”开关提供的代码包装在“while gets (); ... ; print $_ end”中。 '$_' 是一个 Perlish 变量,保存最近读取的行。
I think Ruby is the dedicated application you're looking for:
The data:
The scriptlet:
The magic sauce is the "-p" switch. It wraps the code provided with the "-e" switch in "while gets (); ... ; print $_ end". '$_' is a Perlish variable which holds the most recently read line.
在 Perl 中:
In Perl:
由于我希望用尽可能多的编程语言来回答这个问题,因此这里是 JavaScript 解决方案:
请参阅 来自 MDC 的文档 了解有关函数参数的详细信息。您将获得子匹配和匹配偏移量作为附加参数。
这是Python解决方案:
Since I want this question answered in as many programming languages as possible, here is the JavaScript solution:
See the documentation from MDC for details on the function parameters. You get submatches and the match offset as additional parameters.
Here is the Python solution: