1

I currently have a validation expression that almost works the way I want it to, only I am having trouble allowing spaces at the beginning of some rows. I'd like to support unlimited spaces at the beginning of rows.

Here is an example and the expression that I am having trouble with: ^(?=.?[ \t]([., \t]))(?:[1-9][0-9](?:[ \t]\1[ \t][1-9][0-9])+[ \t]*\r?\n?)+$

Here is the example string I'd like to match:

10 11 12 13 14 30
 9 41 42 44 46 48
10 11 12 13 14 30

My first question which explains what I want to do specifically is found: here

justinpees
  • 420
  • 5
  • 20

3 Answers3

2

As an advanced topic, this will be a little difficult to understand, but here goes.

^\s*[1-9][0-9]*\s*(?=([., \t]))(?:\s*(?:\1|\r?\n)\s*[1-9][0-9]*)+\s*$

You have a unique problem since you are trying to validate all the rows
as a single string.
The problem comes when the delimiter is not available at the end of
a row.

To get around that, use an alternation with the backreference (delimiter)
or a line break.

As for whitespace at the beginning of string, just intersperse with \s.

See here https://regex101.com/r/nir0uI/1 and here https://regex101.com/r/nir0uI/2

Formatted

 ^ 
 \s* 
 [1-9] [0-9]* 
 \s* 
 (?=                                # Lookahead for delimiter.
      ( [., \t] )                   # (1)
 )
 (?:
      \s* 
      (?: \1 | \r? \n )
      \s*       
      [1-9] [0-9]* 
 )+
 \s*  
 $ 
  • Wow a true genius thanks so much!!! Will I run into any problems using tabs as delimiters with this solution? – justinpees Aug 10 '17 at 03:06
  • Also, would it be hard to accept the delimiter at the end of each line? I see that spaces can be added to the end of each line so I pressure that tabs would also work. But how about a single comma (or space-comma) and dot (or space-dot) at the end of each line? depending on which delimiter is used. I know this could be complicating things much more. Tell me if it's too much. – justinpees Aug 10 '17 at 03:13
  • 1
    @justinpees - The regex101 links show the delimiter (group 1) in green highlight. The way it is now, there are 3 conditions around the line break (\r?\n). `No delimiter` or `Delimiter-line break` or `Line break-delimiter`. See https://regex101.com/r/Vll1fT/1. If you want to change one of those conditions, let me know. –  Aug 10 '17 at 12:38
  • thanks again so much, I think I had another question. I'll send out a comment soon when I remember what it was. – justinpees Aug 10 '17 at 15:20
  • do you know if it's possible to make a ValidationExpression like this for when I ask users to upload a .txt file? I'd like to validate the content inside the uploaded .txt file. I will make a new question for this. I'd like to know if it's possible first. – justinpees Aug 10 '17 at 16:39
1
\s

might help at the beginning of your expression.

botjaeger
  • 93
  • 8
1

Add zero or more whitespace to the front of your regex:

^\s*<your regex here>
Bohemian
  • 412,405
  • 93
  • 575
  • 722