正则表达式搜索和替换,其中替换是搜索词的mod [英] Regex search and replace where the replacement is a mod of the search term

查看:105
本文介绍了正则表达式搜索和替换,其中替换是搜索词的mod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到解决方案,并且非常确定正则表达式会支持它。我只是想不起来正则表达式领域中这个概念的名称。



我需要搜索并替换特定模式的字符串,但是模式可以不同并且替换需要记住要替换的内容。



例如,说我有一个任意字符串:134kshflskj9809hkj



我想用括号
括起来,所以结果是:(134)kshflskj(9809)hkj



查找数字很简单足够,但是如何包围它们?



任何人都可以提供样品或为我指明正确的方向吗?

解决方案

以多种语言显示:

  // C#:
字符串结果= Regex.Replace(input,@(\d +),($ 1));
// JavaScript:
thestring.replace(/(\d +)/ g,‘($ 1)’);
// Perl:
s /(\d +)/($ 1)/ g;
// PHP:
$ result = preg_replace( /(\d +)/,‘($ 1)’,$ input);

(\d +)的括号将其设为组,特别是第一个(并且仅在这种情况下)该组,可以是后引用在替换字符串中。在某些实现中,必须使用 g 标志,以使其在单个字符串中多次匹配。替换字符串相当相似,尽管某些语言将使用 \1 而不是 $ 1 ,而某些语言将两者都允许。 / p>

i'm having a hard time finding a solution to this and am pretty sure that regex supports it. i just can't recall the name of the concept in the world of regex.

i need to search and replace a string for a specific pattern but the patterns can be different and the replacement needs to "remember" what it's replacing.

For example, say i have an arbitrary string: 134kshflskj9809hkj

and i want to surround the numbers with parentheses, so the result would be: (134)kshflskj(9809)hkj

Finding numbers is simple enough, but how to surround them?

Can anyone provide a sample or point me in the right direction?

解决方案

In some various langauges:

// C#:
string result = Regex.Replace(input, @"(\d+)", "($1)");
// JavaScript:
thestring.replace(/(\d+)/g, '($1)');
// Perl:
s/(\d+)/($1)/g;
// PHP:
$result = preg_replace("/(\d+)/", '($1)', $input);

The parentheses around (\d+) make it a "group" specifically the first (and only in this case) group which can be backreferenced in the replacement string. The g flag is required in some implementations to make it match multiple times in a single string). The replacement string is fairly similar although some languages will use \1 instead of $1 and some will allow both.

这篇关于正则表达式搜索和替换,其中替换是搜索词的mod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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