2016-08-02 2 views
3

처음 C++에서 정규 표현식을 사용해 보았습니다. 이스케이프 시퀀스에 대해서는 약간 혼란 스럽습니다. 나는 단순히 문자열의 시작 부분에 점을 맞추려고합니다. ".^\\\"그 동안 나는 표현 사용하고, 작동하지만 내 컴파일러 (g ++는) 경고를 생성합니다 ".^\\"나는 예를 들어, 사용하고있는 경우C++ 정규식, 알 수없는 이스케이프 시퀀스 '.' 경고

warning: unknown escape sequence '\.' 
     regex self_regex("^\\\."); 
          ^~ 

을, 그것은 경고를 생성하지 않지만 그 정규식은 내가하고자하는 것과 일치하지 않습니다.

왜 내가 세 개의 백 슬래시를 사용해야하는지 이해하지 못한다. 두 개가 "\"로 충분하지 않아야한다. 첫 번째 백 슬래시가 두 번째 백 슬래시를 이스케이프하므로 실제로 검색합니다.하지만 작동하지 않습니다. 누군가 나를 위해 이것을 분명히 해줄 수 있습니까?

코드 :

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

using namespace std; 

int main(void){ 
    DIR *dir; 
    string path = "/Users/-----------/Documents/Bibliothek/MachineLearning/DeepLearning/ConvolutionalNeuralNetworks/CS231n 2016/Assignments/assignment3/assignment3/cs231n"; 
    regex self_regex("^\\\.+"); 
    struct dirent *ent; 
    dir = opendir(path.c_str()); 
    if ((dir = opendir(path.c_str())) != NULL){ 
     while ((ent = readdir(dir)) != NULL){ 
      if (regex_search(string(ent->d_name),self_regex)){ 
       cout << "matches regex" << ent->d_name << endl; 
      } 
      else{ 
       cout << "does not match regex " << ent->d_name << endl; 
      } 
     } 
     closedir(dir); 
    } 
    return 0; 
} 

출력 :

코드에서 문자열 리터럴 쓰기
matches regex. 
matches regex.. 
matches regex.DS_Store 
matches regex.gitignore 
does not match regex __init__.py 
does not match regex __init__.pyc 
does not match regex build 
does not match regex captioning_solver.py 
does not match regex captioning_solver.pyc 
does not match regex classifiers 
does not match regex coco_utils.py 
does not match regex coco_utils.pyc 
does not match regex data_utils.py 
does not match regex datasets 
does not match regex fast_layers.py 
does not match regex fast_layers.pyc 
does not match regex gradient_check.py 
does not match regex gradient_check.pyc 
does not match regex im2col.py 
does not match regex im2col.pyc 
does not match regex im2col_cython.c 
does not match regex im2col_cython.pyx 
does not match regex im2col_cython.so 
does not match regex image_utils.py 
does not match regex image_utils.pyc 
does not match regex layer_utils.py 
does not match regex layers.py 
does not match regex layers.pyc 
does not match regex optim.py 
does not match regex optim.pyc 
does not match regex rnn_layers.py 
does not match regex rnn_layers.pyc 
does not match regex setup.py 
+1

관련 코드, 입력 문자열 및 예상되는 동작 전체를 게시하십시오.문자열이 점으로 시작하는지 확인 BTW, 정규식이 필요하지 않습니다. –

+0

'\\\.'는 첫 번째 백 슬래시가 두 번째 백 슬래시를 이스케이프하고 세 번째 백 슬래시가 점을 이스케이프 처리하기 때문에'\\\.'가됩니다. –

+0

'regex self_regex ("^ \\. +");'또는'regex self_regex ("^ \\.");'. 가장 좋은 원시 문자열 리터럴 :'regex self_regex (R "(^ \.)");' –

답변

7

:

"^\\\." 

컴파일러가 규칙 ++은 C에 따라 구문 분석됩니다 실행 파일에 사용될 문자열을 생성하십시오. 예를 들어 \n이 발생하면 실행 파일의 문자열에 대신 줄 바꿈이 포함됩니다. "\\""\"으로 변환되지만 컴파일러는 이 C++로 정의되어 있기 때문에 "\."을 처리하는 방법을 알지 못합니다. 슬래시 다음 문자 (...)에 나열되지 않은

이스케이프 시퀀스 구현 정의 의미론 조건부지지된다.

그래서 당신이 찾고있는 문자열은 두 개의 슬래시입니다 :로 컴파일러에 의해 변형 될 것이다

"^\\." 

:

"^\." 

가 그리고 이것은 regex you're looking for입니다!

참고 : 예를 들어 GCC는 알 수없는 이스케이프 시퀀스 "\.""."으로 변환하므로 실제로 2 ~ 3 개의 bakslashes가 동일한 결과를 생성합니다. 하지 모든 이스케이프 시퀀스는 C의 의미를 ++ 있기 때문에

Online demo

+4

또는 모든 문자열 수준 백 슬래시 이스케이프에 대한 필요성을 제거하는 C + + 11 원시 문자열 (정규 합리적인 방법을 사용하는 유일한 합리적인 방법입니다)를 사용하므로 정규식 이스케이프 'R "(^ \.)"' – ShadowRanger

+0

@ShadowRanger 우수 제안! – Christophe

2

컴파일러에서 경고를 생성합니다. 유효한 이스케이프 시퀀스 목록은 here입니다.

그러나 regex는 '.'을 이스케이프 처리해야합니다. 문자 그대로 '.'와 일치하도록 문자 대신. 탈출 '.' 정규식 패턴에서 앞에 '\'문자 하나를 추가해야합니다. 그러나 단일 '\'는 C++의 이스케이프를 의미하기 때문에 두 개의 백 슬래시 ("\\")를 사용해야합니다. 따라서 올바른 패턴은 "^ \\."입니다.

관련 문제