Search code examples
regexregsub

Trim line from beginning and after certain expression


I have a string "GET /testline HTTP/1.0#015#012U".
String always start with "GET ", and always contains "HTTP/1.0".
Word "/testline" maybe various length and contains symbols and digits.
I need trim string to "/testline" (cut "GET " at the beginning, and cut "HTTP/1.0" and all other symbols after) using regex
How I can do this with regex?


Solution

  • Try this:

    (?<=GET )\S+(?= HTTP\/1\.0)

    (?<=GET ) is Positive lookbehind - Matches a group before the main expression without including it in the result

    (?= HTTP\/1\.0) is Positive lookahead - Matches a group after the main expression without including it in the result.

    Notice: there is a space " " after GET and before HTTP

    const regexPattern = /(?<=GET )\S+(?= HTTP\/1\.0)/g
    const paragraph = 'GET /testline HTTP/1.0#015#012U';
    const found = paragraph.match(regexPattern);
    
    console.log(found)