1

I need to check if a regex pattern matches with all the target string.

For example, if the pattern is '[0-9]+':

  • Target string '123' should result True
  • Target string '123' + sLineBreak should result False

The code should looks like the following:

uses
  System.RegularExpressions;

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

I've tried TRegEx.Match(...).Success and TRegEx.IsMatch without success and I'm wondering if there is an easy way for checking if a pattern matches the whole target string.

I've also tried using ^ - start of line and $ - end of line but without any success.

uses
  System.RegularExpressions;

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

Here you can find an online test demonstrating that if the target string ends with a new line, the regex still matches even using start/end of line.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
Fabrizio
  • 7,603
  • 6
  • 44
  • 104

2 Answers2

1

Make sure the whole string matches:

\A[0-9]+\z

Explanation

--------------------------------------------------------------------------------
  \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

Also, see Whats the difference between \z and \Z in a regular expression and when and how do I use it?

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
-5

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

You can use : ^\d+$

^ start of string

\d+ at lease one or more number of digits

$ end of string

Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44