简体   繁体   中英

Delete part of string in C (regex?)

I have a long string with information like this:

"GET http://www.google.se/ HTTP/1.1\r\n
Host: www.google.se\r\n
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n
Accept-Language: en-us,en;q=0.5\r\n
Accept-Encoding: gzip, deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n
Keep-Alive: 115\r\n
Proxy-Connection: keep-alive\r\n
Cookie: PREF=ID=7d6a62c557413bc8:FF=0:TM=1327968040:LM=1327968040:S=U1A51rCRDDMTF295\r\n
Cache-Control: max-age=0\r\n\r\n"

And i want to get rid of the keep-alive part under the Proxy-Connection.. This is what i'm doing so far:

  1. getting the string (header) in to the function.
  2. Creating a struct with two strings (header and host)
  3. putting the host name from the header in the host part (obviously)
  4. and putting the header in the header part.

And now i want to get rid of the keep-alive part before i put the header in the header-part of the struct.

Any ideas?

And here is some code of what i've done so far. I'm new to C so might not be the most beautiful of code you've seen..

struct ParsedHeader header_parser(char * input) {
  struct ParsedHeader h;
  int status;
  regex_t regex;
  char * result_begin = NULL;

  regcomp(&regex, "host:", REG_EXTENDED|REG_ICASE|REG_NOSUB);
  if((status = regexec(&regex, input, (size_t) 0, NULL, 0)) == 0) {
    char end = '\r';
    char * header = malloc(strlen(input));

    char * begin = "host:";

    size_t result_size = 0;
    memcpy(header, input, strlen(input));
    to_lower(input, header, strlen(input));
    result_begin = (strstr(header, begin) + 6);

    char * result_end = strchr(result_begin, end);
    result_end[0] = '\0';
    //char result[strlen(result_begin)] = result_begin;
    free(header);
  }
  regfree(&regex);

  h.header = input;
  h.host = result_begin;

  return h;
}

If I understand your question correctly, you want to remove only the "Keep-Alive" string. Do it like this:

// assume buffer contains the long input string
char *pBegin; 
char *pEnd;
pBegin = strstr(buffer, "Keep-Alive:");
if (pBegin)
{
    pEnd = strstr(pBegin, "\r\n");
    if (pEnd)
        strcpy(pBegin, pEnd+2);
}

However, if what you want to do is remove the "keep-alive" string from the Proxy-Connection header, a similar solution works:

char *pBegin; 
char *pEnd;
pBegin = strstr(buffer, "Proxy-Connection:");
if (pBegin)
{
    pBegin = strstr(pBegin, "keep-alive");
    if (pBegin)
        strcpy(pBegin, pBegin+strlen("keep-alive"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM