warning: unknown escape sequence '\

爷,独闯天下 提交于 2021-02-16 21:32:22

问题


I'm trying to run a regex through a system command in the code, I have gone through the threads in StackOverflow on similar warnings but I couldn't understand on how to fix the below warnings, it seems to come only for the closed brackets on doing \\}. The warnings seem to disappear but not able to get the exact output in the redirected file.

#include<stdio.h>


int main(){

        FILE *in;
        char buff[512];

if(system("grep -o '[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}' /home/santosh/Test/text >t2.txt") < 0){
                printf("system failed:");
                exit(1);
        }
}

Warnings:

dup.c:9:11: warning: unknown escape sequence '\}'
dup.c:9:11: warning: unknown escape sequence '\}'
dup.c:9:11: warning: unknown escape sequence '\}'
dup.c:9:11: warning: unknown escape sequence '\}'
dup.c: In function 'main':

回答1:


In C string literals the \ has a special meaning, it's for representing characters such as line endings \n. If you want to put a \ in a string, you need to use \\.

For example

"\\Hello\\Test"

will actually result in "\Hello\Test".

So your regexp needs to be written as:

"[0-9]\\{1,3\}\\\\.[0-9]\\{1,3\}\\\\.[0-9]\\{1,3\\}\\\\.[0-9]\\{1,3\\}"

instead of:

"[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}\\.[0-9]\{1,3\}"

Sure this is painful because \ is used as escape character for the regexp and again as escape character for the string literal.

So basically: when you want to put a \ you need to write \\.



来源:https://stackoverflow.com/questions/42022735/warning-unknown-escape-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!