Regex printable ascii plus newline and carriage return

Viewed 154

I am writing a validator function in javascript for data entry. I have two conditions I need to test for.

Case 1: All printable ASCII characters between 32 and 126 Case 2: All printable ASCII characters between 32 and 126 plus carriage return and new line.

Here is my regex for Case 1:

/^(?=[ -~])[^\r\n]*$/

Is this suitable for Case 2?

/^(?=[\n-~])[^\013\014\016-\037]*$/
2 Answers

You can use

  1. ^[ -~]*$, this pattern matches any printable ASCII chars without carriage return and a line feed chars because they are simply out of this range.

See this regex demo.

  1. ^[ -~\r\n]*$ will do because -~ defines the range described above + a line feed and a carriage return.

See this regex demo.

Also, check the ASCII table codes to see what is included in the ranges above.

You're missing \r (return carriage) in the second one

/^(?=[\n\r-~])[^\013\014\016-\037]*$/
Related