apexlol
apexlol

Reputation: 130

Regex string validation

Trying to write some regex to validate a string, where null and empty strings are not allowed, but characters + new line should be allowed. The string I'm trying to validate is as follows:

First line \n
Second line \n

This is as far as i got:

^(?!\s*$).+

This fails my validation because of the new line. Any ideas? I should add, i cannot use awk.

Upvotes: 0

Views: 60

Answers (2)

lukasz.kiszka
lukasz.kiszka

Reputation: 163

Try this pattern:

([\S ]*(\n)*)*

Upvotes: 0

ctwheels
ctwheels

Reputation: 22817

Code

The following regex matches the entire line.
See regex in use here

^[^\r\n]*?\S.*$

The following regexes do the same as above except they're used for validation purposes only (they don't match the whole line, instead they simply ensures it's properly formed). The benefit of using these regexes over the one above is the number of steps (performance). In the regex101 links below they show as 28 steps as opposed to 34 for the pattern above.
See regex in use here

^[^\r\n]*?\S

See regex in use here

^.*?\S

Results

Input

First line \n
Second line \n



s

Output

Matches only

First line \n
Second line \n
s

Explanation

  • ^ Assert position at the start of the line
  • [^\r\n]*? Match any character not present in the set (any character except the carriage return or line-feed characters) any number of times, but as few as possible (making this lazy increases performance - less steps)
  • \S Match any non-whitespace character
  • .* Match any character (excludes newline characters) any number of times
  • $ Assert position at the end of the line

Upvotes: 1

Related Questions