정규 표현식 질문입니다.

metalwolf의 이미지

다름이 아니라 posix 정규 표현식 함수를 사용하여 pattern이 가리키는 offset

을 찾고 싶은데 값이 대체 어디로 나오는지 알수 가 없군요. 샘플 예제는

regexec예제를 수정하여 올립니다. 제가 생각하기론 regexec 에서 re에

넣어져야 될것 같은데 그렇지가 않네요... 아시는 분 있으시면 우매한 저를

깨우쳐 주시기 바랍니다. ^___^;

#include <iostream.h>
#include <regex.h>
#include <string.h>

using namespace std;
int
match(const char *string, char *pattern)
{
#include <iostream.h>
#include <regex.h>
#include <string.h>

using namespace std;

int
match(const char *string, char *pattern)
{
int status;
regex_t re;
regmatch_t nm;

if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
return(0); /* Report error. */
}
long subCount = re.re_nsub;
status = regexec(&re, string, 0, NULL, 0);
cout << string << endl;
regfree(&re);
if (status != 0) {
return(0); /* Report error. */
}
return(1);
}

int main(void )
{
string strTest = "POST http://korea.com HTTP/1.0
Host: kldp.omms.com
Content-Type: multipart/related; boundary=\"NextPart_000_0028_01C19839.84698430\";
type=text/xml; start=\"</tnn-200102/mm7-submit>\"
Content-Length: nnnn
SOAPAction: \"\"
-- NextPart_000_0028_01C19839.84698430
Content-Type:text/xml; charset=\"utf-8\"
Content-ID: </tnn-200102/mm7-submit>
<?xml version='1.0'?>";

match( strTest.c_str(), "http:");
}

niemand의 이미지

#define MAX_NUM 10

뭐 우선 임의의 숫자를 define하신 후

코딩하신 부분 중에서 아래처럼 고치시면 될 겁니다.

regmatch_t nm[MAX_NUM];
status = regexec(&re, string, MAX_NUM, nm, 0);

그 이후에 매칭이 성공한 경우에 한번

printf("S_offset=[%d],E_offset[%d]\n", nm[0].rm_so, nm[0].rm_eo);

라고 해 보시면 찾고자 했던 스트링이 문장 내에서 어느 위치에 있는지
offset이 나올 겁니다.
이제 원래 문장에서 그 offset을 참고로 해서 잘라내면 되시구요.

metalwolf의 이미지

Quote:
그 이후에 매칭이 성공한 경우에 한번
코드:

printf("S_offset=[%d],E_offset[%d]\n", nm[0].rm_so, nm[0].rm_eo);

라고 해 보시면 찾고자 했던 스트링이 문장 내에서 어느 위치에 있는지
offset이 나올 겁니다.

niemand님 말씀대로 코딩했습니다. 헌데
status 는 0을 리턴합니다. 찾았는데 offset이 항상 의미없는 값으로 고정

되어 있더군요. rm_so 는 항상 1 , rm_eo 는 항상 0입니다.

전혀 offset하고 연관성이 없는 값이 출력 되어집니다.

^____^; 방가여

niemand의 이미지

리눅스에서 gcc 2.96 에서 테스트한
제 샘플소스를 올립니다.

사실 metalwolf님의 소스를 다 못 보고 관련된 코딩 부분만을
봐서 ^^;;;

참고가 되길 바라겠습니다.

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#define        NUMBER        10
int main(int argc, char *argv[]){
        regex_t mregex;
        regmatch_t mt[NUMBER];
        int reti;
        char msgbuf[100];

/* Compile regular expression */
        reti = regcomp(&mregex, "abc", 0);
        if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }

/* Execute regular expression */
        reti = regexec(&mregex, "clbabcacdfe", NUMBER, mt, 0);
        if( !reti ){
                puts("Match");
                printf("[%d][%d]\n",mt[0].rm_so, mt[0].rm_eo);
        }
        else if( reti == REG_NOMATCH ){
                puts("No match");
        }
        else{
                regerror(reti, &mregex, msgbuf, sizeof(msgbuf));
                fprintf(stderr, "regex match failed: %s\n", msgbuf);
                exit(1);
        }

/* Free compiled regular expression if you want to use the regex_t again */
        regfree(&mregex);

        return 0;
}
niemand의 이미지

if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {

위 부분에서 REG_NOSUB을 꼭 쓰셔야 되는 이유가 없다면 한번 빼보시죠.
저는 저게 특별히 뭘 하는지 모르겠는데.. ^^;;
저도 저 옵션을 넣으니까 문제가 생기더군요.

언제 쓰는 건지 아시면 저도 좀 알려주시구요

pynoos의 이미지

잘 안되면, 정규식을

(http:[^ \t]+)

로 바꿔보세요. 그리고 nm 배열 인덱스는 1 번으로 참조해보시기 바랍니다.

괄호가 있어야 regmatch_t 배열이 효과를 봅니다.

괄호가 없어도 0 번은 전체 매치이기 때문에 잘될 것도 같은데...

배열의 크기를 10으로 잡으셨는데 이는 괄호수보다 1 크면 됩니다.

물론 괄호를 사용한다면 REG_NOSUB 가 없어야합니다.

metalwolf의 이미지

모두들 답변 감사합니다.

Quote:
위 부분에서 REG_NOSUB을 꼭 쓰셔야 되는 이유가 없다면 한번 빼보시죠.
저는 저게 특별히 뭘 하는지 모르겠는데.. ^^;;
저도 저 옵션을 넣으니까 문제가 생기더군요.

niemand 말씀처럼 REG_NOSUB를 없애니까 잘 수행이 됩니다.

이 flag에 대한 설명은 "괄호르 찾은 부분 영역 기억 하지 않기 " 인데 어떤

얘기인줄은 모르겠군요...

pynoos 말씀중에 괄호를 사용한다면 REG_NOSUB를 없애야 된다는 말이

이해가 되지 않습니다. 여기서 괄호는 어떤 것을 의미하는지?

^____^; 방가여

pynoos의 이미지

metalwolf wrote:
모두들 답변 감사합니다.

pynoos 말씀중에 괄호를 사용한다면 REG_NOSUB를 없애야 된다는 말이

이해가 되지 않습니다. 여기서 괄호는 어떤 것을 의미하는지?

제가 제시한 정규식을 보시면 괄호가 있고 그 괄호는 매치되는 위치를 세분화하여 떼어 낼 수가 있습니다. 그렇게 정규식에 부분 매치하여 사용되는 경우에만 REG_NOSUB 를 사용하라는 것입니다.

위에서 제시하신 예제에서 혹시 URL 부분만 떼어내고 맨 뒤의 HTTP/1.0은 관심없다면 정규식을 이용해서 정확히 URL만 떼어 낼 수가 있는 것이죠.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.