【问题标题】:How to check if a RegEx matches all the target string?如何检查正则表达式是否匹配所有目标字符串?
【发布时间】:2020-10-21 10:59:46
【问题描述】:

我需要检查一个正则表达式模式是否与所有目标字符串匹配。

例如,如果模式是'[0-9]+'

  • 目标字符串'123' 应该是True
  • 目标字符串'123' + sLineBreak 应该是False

代码应如下所示:

uses
  System.RegularExpressions;

begin
  if(TRegEx.IsFullMatch('123' + sLineBreak, '[0-9]+'))
  then ShowMessage('Match all')
  else ShowMessage('Not match all');
end;

我试过TRegEx.Match(...).SuccessTRegEx.IsMatch 都没有成功,我想知道是否有一种简单的方法可以检查模式是否与整个目标字符串匹配。

我也尝试过使用^ - start of line$ - end of line,但没有任何成功。

uses
  System.RegularExpressions;

begin
  if(TRegEx.IsMatch('123' + sLineBreak, '^[0-9]+$'))
  then ShowMessage('Match all')
  else ShowMessage('Not match all');
end;

Here 你可以找到一个在线测试,证明如果目标字符串以新行结尾,即使使用行首/行尾,正则表达式仍然匹配。

【问题讨论】:

  • 您尝试过使用锚点吗? ^[0-9]+$
  • @Thefourthbird:是的,但它并不总是有效,我已经更新了问题中的示例
  • Strings Ending with a Line Break 部分解释了为什么您应该使用 \z 而不是 $ 以避免在上一个示例中匹配。
  • @BrakNicku:看来\z解决了我的问题,谢谢

标签: regex delphi delphi-xe7


【解决方案1】:

确保整个字符串匹配:

\A[0-9]+\z

说明

--------------------------------------------------------------------------------
  \A                       the beginning of the string
--------------------------------------------------------------------------------
  [0-9]+                   any character of: '0' to '9' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \z                       the end of the string

另外,请参阅Whats the difference between \z and \Z in a regular expression and when and how do I use it?

【讨论】:

  • \A^有什么区别?
  • 我找到了答案here。 +1 并感谢您的回答
【解决方案2】:

var str = '123';
var sLineBreak = '\n';

console.log(str.match(/^\d+$/)); //123
console.log((str + 'b').match(/^\d+$/)); //123b
console.log((str + sLineBreak).match(/^\d+$/)); //123\n

您可以使用:^\d+$

^ 字符串开头

\d+至少一位或多位数字

$ 字符串结尾

【讨论】:

  • 当至少有一个必须发生时(根据+),您不能说“任何”。
  • 不幸的是,如果目标字符串以新行结尾,正则表达式仍然匹配,我还通过添加在线测试更新了问题
  • 那不是 Delphi。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多