0

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.

1
  • ^[^\r\n]*?\S.*$ or at the very least (if it's a simple thing of true/false that you're trying to get ^[^\r\n]*?\S) Commented Dec 13, 2017 at 18:33

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, very informative answer, sadly it did not work, but it has lead me to the correct answer! If you edit your answer with ^[^\ ]*?\S.*$ i will mark it as accepted. Cheers, Ape.
0

Try this pattern:

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

4 Comments

Whilst this works where there are 2 lines, it fails when there is a single line and no new line character. Close though!
What is the purpose of ?! in the set?
@ctwheels thanks for questions. ?! is unnecessary - is paste it becouse author of questions use it in his example pattern.
@lukasz.kiszka it's used in the context of a group (not a set), the OP's use of (?!) defines a negative lookahead (ensures what follows doesn't match what the group contains). Your pattern can effectively be shortened to ([\S ]*\n*)*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.