正则表达式,替换字符的代码
时间: 2023-04-03 16:04:20 浏览: 121
可以使用正则表达式的替换函数,例如在 C 语言中可以使用 regex.h 库中的 regcomp()、regexec()、regfree() 函数来进行正则表达式的匹配和替换。以下是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
int main()
{
char *pattern = "hello";
char *replacement = "world";
char *input = "hello, world!";
regex_t regex;
regcomp(®ex, pattern, REG_EXTENDED);
size_t nmatch = 1;
regmatch_t pmatch[1];
int status = regexec(®ex, input, nmatch, pmatch, 0);
if (status == 0) {
char *output = malloc(strlen(input) + strlen(replacement) + 1);
strncpy(output, input, pmatch[0].rm_so);
strcpy(output + pmatch[0].rm_so, replacement);
strcpy(output + pmatch[0].rm_so + strlen(replacement), input + pmatch[0].rm_eo);
printf("%s\n", output);
free(output);
} else {
printf("No match\n");
}
regfree(®ex);
return 0;
}
```
以上代码将会把字符串中的 "hello" 替换为 "world",输出结果为 "world, world!"。