正则表达式的部分匹配 [英] Partial matching of Regular expression

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

问题描述

我有一个逐步构建的String。在构建字符串时,它通过正则表达式整体匹配,当找到匹配项时,执行某个任务。

I have a String that is incrementally built. While the string being built, it is matched as a whole by a regular expression and when a match is found, a certain task is performed.

我的要求是:如果在在字符串构建过程的中间,发现无法找到完全匹配,然后应该重置字符串并重新启动构建过程。

My requirement is: If in the middle of the string building process it is found that there is no way an exact match will be found, then the string should be reset and the build process should be re-initiated.

例如,如果正则表达式是mada12gaskar,并且将char 3添加到现有字符串mada1字符串应该被清除,构建过程应该重新开始,因为mada13永远不会与mada12gaskar匹配。这可以通过Java正则表达式API吗?

For example if a regular expression is "mada12gaskar" and when a char "3" is added to an existing string "mada1" the string should be cleared and the build process should start over again as "mada13" will never match with "mada12gaskar". Is this possible through Java regex API?

推荐答案

我想我找到了解决问题的可能方法。

I think I found a possible solution to your problem.

看看 Matcher#hitEnd() 方法:


如果返回true,则返回true搜索引擎在此匹配器执行的
最后一次匹配操作中被输入结束。

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

当此方法返回true时,则有可能更多输入
会改变上次搜索的结果。

When this method returns true, then it is possible that more input would have changed the result of the last search.

现在,只需将正则表达式与您的尚未匹配使用 Matcher (可通过 Pattern 实例获得)构建的字符串,并查看结果:

Now, simply match the regexp against your not-yet-fully-constructed String using a Matcher (obtainable via a Pattern instance) and look at the results:


  • 如果匹配,你有你的赢家

  • 如果不匹配,请查看 hitEnd()

    • 如果它是 tru e ,构建更多String并再试一次

    • 如果它是 false ,则当前的String永远不会匹配,你可以放弃并重新开始

    • if it matched, you have your winner
    • if it didn't match, look at hitEnd():
      • if it's true, build more String and try again
      • if it's false, the current String could never be matched, you can drop it and start over

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

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