正则表达式申请退格字符 [英] Regular expression to apply backspace characters

查看:190
本文介绍了正则表达式申请退格字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Telnet客户端来的字符串。该字符串包含了我需要申请退格字符。每个退格应该删除一个以前输入的字符

I have a string coming from a telnet client. This string contains backspace characters which I need to apply. Each backspace should remove one previously typed character.

我想这样做在一个单一的替换使用正则表达式:

I'm trying to do this in a single replace using regular expression:

string txt = "Hello7\b World123\b\b\b";
txt = Regex.Replace(txt, ".\\\b", "", RegexOptions.ECMAScript);



这会导致你好World12。当然,我想十二五要过删除,但它显然不我的表达式。

Which results in "Hello World12". Of course, I want "12" to be removed too, but it obviously doesn't match my expression.

在某种程度上,它应该重复替换,直到没有更多的比赛。如何用一个正则表达式来实现这一目标的任何想法?

In some way, it should repeat replacing until there are no more matches. Any ideas on how to achieve this with a single regular expression?

推荐答案

这是基本的我们如何匹配的Java正则表达式一个NB ^ ^ N ,所以我们莫不是重用的答案是:

This is basically a variant of How can we match a^n b^n with Java regex?, so we could reuse its answer there:

var regex = new Regex(@"(?:[^\b](?=[^\b]*((?>\1?)[\b])))+\1");
Console.WriteLine(regex.Replace("Hello7\b World123\b\b\b", ""));

此外,在.NET正则表达式引擎支持的均衡组的,所以我们可以用不同的方式:

Additionally, the .NET regex engine supports balancing groups, so we could use a different pattern:

var regex = new Regex(@"(?<L>[^\b])+(?<R-L>[\b])+(?(L)(?!))");



(这意味着:

(This means:


  1. 匹配一个或多个非退格,名称为L赋予它们,

  2. 再接着一个或多个退格,名称为R指派他们,条件是每一个R必须有一个相应的L,

  3. 如果有任何L的左,放弃了比赛(如(?! )匹配任何操作)。

  1. Match one or more non-backspaces, assigning them with the name "L",
  2. then followed one or more backspaces, assigning them with the name "R", with the condition that every "R" must have one corresponding "L",
  3. if there are any "L"s left, abandon the match (as (?!) matches nothing).

这篇关于正则表达式申请退格字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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