Home > Back-end >  Regex for extracting every character except numbers and specific words at the end of string
Regex for extracting every character except numbers and specific words at the end of string

Time:05-21

I want to extract everything starting with // till numbers ending with specific texts given this string below:

// Peter F. Hamilton|Pandora's Star 200 OK

Numbers and texts are here Response.status and Response.statusText. I have tried this regex which works for this specific string

\/\/.*[^200 OK]

But, status and statusTextcan be various, and I need a regex that works for all the cases. I have tried this regex with the non-capturing group but it does not seem to work. What am I doing wrong?

\/\/.*(?:\d \s(OK|Not Found|Continue))

CodePudding user response:

Http status codes range from 1xx to 5xx. Generally, we can try the following approach:

var input = "// Peter F. Hamilton|Pandora's Star 200 OK";
var text = input.match(/(\/\/.*) [1-5][0-9]{2}( \w ) /, input)[1];
console.log(text);

CodePudding user response:

Since you are concerned with the middle text, you can use the following:

\/\/(.*)(?:(?:\d\d\d).*)$

This will give you the desired text in group 1 (with potentially extra spaces that you can trim).

Since http status codes are three digits, we can assume the last occurrence of three digits in the input string is where the status code starts, and everything after that is the status code description.

  • Related