匹配字符串正则表达式指数在那里匹配失败 [英] Regex index in matching string where the match failed

查看:124
本文介绍了匹配字符串正则表达式指数在那里匹配失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以提取特定字符串中的索引位置,一个正则表达式试图匹配它的时候失败了?

I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it?

例如,如果我的正则表达式是ABC,我试图匹配以ABD比赛将在指数2失败。

For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2.

编辑澄清。我需要这样做的原因是为了让我简化我的应用程序的分析组件。该应用程序是一个Assmebly语言教学工具,让学生编写,编译和这样的程序执行汇编。

Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs.

目前我有一个标记生成器类转换使用正则表达式的字符串输入到令牌。这工作得很好。例如:

Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example:

标记生成器将产生如下标记给出下面的输入=INP:X:结果:

The tokenizer would produce the following tokens given the following input = "INP :x:"
:

Token.OPCODE,Token.WHITESPACE,Token.LABEL,Token.EOL

Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL

这些令牌,然后分析,以确保它们符合语法对于给定的声明。目前,这是使用IF语句完成的,并且证明繁琐。这种方法的好处是,我可以提供详细的错误信息。即

These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E

if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label"); }



我想用正则表达式来定义的语法,而不是恼人的IF语句。但在这样做,所以我失去了返回详细的错误报告的能力。因此,我希望至少告知发生错误​​的用户。

I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.

推荐答案

我跟科林同意雅戈尔,我不认为这不是可能与现有的正则表达式类。但是,我认为这是可行的,如果你愿意汗水一点:

I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little:


  1. 获取正则表达式类的源代码
    (例如:
    http://www.codeplex.com/NetMassDownloader
    下载。净源)。

  2. 更改代码以与失败指数只读
    属性。

  3. 确保您的代码使用该正则表达式
    ,而不是微软。

  1. Get the Regex class source code (e.g. http://www.codeplex.com/NetMassDownloader to download the .Net source).
  2. Change the code to have a readonly property with the failure index.
  3. Make sure your code uses that Regex rather than Microsoft's.

这篇关于匹配字符串正则表达式指数在那里匹配失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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