2015-07-10 84 views
1

我想使用正则表达式解析url参数。使用正则表达式解析URL参数

这里是我的网址:

http://127.0.0.1/privet/register?action=cancel&[email protected]

虽然简单,可能有人帮助我写了下面的URL参数的正则表达式:

action=cancel&user=xx.gcp234%40gmail.com 

这里是我的正则表达式: “/^([\az.-])\=([\az.-])$/

我只需要打印以下信息:

行动=取消

用户= [email protected]

和发送此回作为JSON格式的字符串。

任何帮助将不胜感激。

感谢

+1

你应该*修改你的问题*并且使用到目前为止您尝试过的表达方式。 “我的正则表达式有什么问题?”肯定会得到比你问的更好的反馈,这从根本上归结为“为我编写正则表达式”。 – WhozCraig

+0

@ WhozCraig ..感谢您的建议。我已经相应地更新了我的帖子。 – ap6491

回答

2

使用regex.h库(在UNIX中可用)和返回的参数如下=&分离咬的位置,距离Corona688的帖子通过了关于Unix Linux Forums。如果你不使用Unix,你必须找到并下载一个正则表达式库。

#include <stdio.h> 
#include <regex.h> 
int main(void) 
{ 
     regex_t reg; 
     const char *regex="([^=&?]+)=([^&]+)"; 
     const char *str="http://127.0.0.1/privet/register?action=cancel&[email protected]"; 
     regmatch_t matches[16]; 

     regcomp(&reg, regex, REG_EXTENDED); 

     if(regexec(&reg, str, 16, matches, 0) == 0) 
     { 
       printf("regex /%s/ matched string '%s' at bytes %d-%d\n", 
         regex, str, matches[0].rm_so, matches[0].rm_eo); 
     } 
     else 
       printf("regex /%s/ does not match string '%s'\n", regex, str); 
} 
+0

匹配[1]返回什么?它是否会返回user = [email protected]? – ap6491

+0

是的,以及取消。 –

+0

我想解析在C中的上述网址,我得到一个错误说:“错误:格式太多的参数[-Werror =格式额外参数] sscanf(文本,”行动=(\ w *)&用户= (\ S *)“,action,user)”这是我的代码: \t char text [] =“http://127.0.0.1/privet/register?action=start&[email protected]”; \t char操作[10]; \t char用户[25]; \t \t sscanf(text,“action =(\ w *)&user =(\ S *)”,action,user); – ap6491

0

下面的代码片段解析URL

http://127.0.0.1/privet/register?action=cancel&[email protected]

regex_t reg; 
      const char *regex = "([^=&?]+)=([^&]+)"; 
      //const char *regex = "action=(\w*)&user=(\S*)"; 
      const char *str = "http://127.0.0.1/privet/register?action=cancel&[email protected]"; 
      LOGDEBUG("r->uri : %s\n", r->unparsed_uri); 
      size_t maxGroups = 10; 
      regmatch_t groupArray[maxGroups]; 

      regcomp(&reg, regex, REG_EXTENDED); 

      if (regexec(&reg, str, maxGroups, groupArray, 0) == 0) { 
       unsigned int g = 0; 
       for (g = 0; g < maxGroups; g++) { 
        if (groupArray[g].rm_so == (size_t) -1) 
         break; // No more groups 

        char sourceCopy[strlen(str) + 1]; 
        strcpy(sourceCopy, str); 
        sourceCopy[groupArray[g].rm_eo] = 0; 
        LOGDEBUG("Group %u: [%2u-%2u]: %s\n", g, groupArray[g].rm_so, 
          groupArray[g].rm_eo, sourceCopy + groupArray[g].rm_so); 

} 

这将返回匹配组。