justinpees
justinpees

Reputation: 420

How to allow spaces in the beginning of each row using regex?

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

Upvotes: 1

Views: 714

Answers (3)

user557597
user557597

Reputation:

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*  
 $ 

Upvotes: 2

Bohemian
Bohemian

Reputation: 425248

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

^\s*<your regex here>

Upvotes: 1

botjaeger
botjaeger

Reputation: 95

\s

might help at the beginning of your expression.

Upvotes: 1

Related Questions