Home > Net >  Regex - Check first character of every line
Regex - Check first character of every line

Time:01-21

I am searching for a regex that would do the following:

  1. Check if the first character of the line is a - or :
  2. Check the succeeding characters of the line and it should be alphanumeric and whitespace are acceptable. There are maximum 10 characters per line.
  3. Should impose 5 max lines

I have been working on the following regex: ^[^:-][a-zA-Z0-9]{7}$ --> for nos. 1 & 2 condition. However, it seems like it is not working .

Then for the number of lines, I searched at https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s10.html . The regex below would check the number of lines.

^(?:[^\r\n]*(?:\r\n?|\n)){0,4}[^\r\n]*$

I don't know how to combine all the conditions I mentioned in a regex. It's my first time working on it.

Not Acceptable. There is - in 2nd line

Hello01

-Hello01

Hello0

Hello03

Hello04

Not Acceptable. More than 5 Lines

Hello01

-Hello01

Hello02

Hello03

Hello04

Hello05

Acceptable. No - or : in first character of the line

Hello01

Hello02

Hello03

Hello04

Hello05

CodePudding user response:

You can use

^[^\r\n:-][a-zA-Z0-9]{0,9}(?:\r?\n[^\r\n:-][a-zA-Z0-9]{0,9}){0,4}$

Details:

  • ^ - start of string
  • [^\r\n:-] - any char that is not CR, LF, : and -
  • [a-zA-Z0-9]{0,9} - zero to nine alnum chars
  • (?:\r?\n[^\r\n:-][a-zA-Z0-9]{0,9}){0,4} - zero to four occurrences of
    • \r?\n - CRLF or LF ending
    • [^\r\n:-][a-zA-Z0-9]{0,9} - any char that is not CR, LF, : and - and then zero to nine alnum chars
  • $ - end of string.
  •  Tags:  
  • Related