C言語でテキストからデータを抽出する方法は何ですか?
文本からデータを抽出する場合は、C言語の文字列処理関数と正規表現ライブラリを使用することができます。以下は数字を抽出するためのサンプルコードです。
#include <stdio.h>
#include <string.h>
#include <regex.h>
int main() {
char text[] = "The price of the product is $99.99";
char pattern[] = "\\$([0-9]+\\.[0-9]+)";
regex_t regex;
regmatch_t matches[2];
if(regcomp(®ex, pattern, REG_EXTENDED) != 0) {
printf("Error compiling regex\n");
return 1;
}
if(regexec(®ex, text, 2, matches, 0) == 0) {
char price[20];
strncpy(price, text + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
price[matches[1].rm_eo - matches[1].rm_so] = '\0';
printf("Price: %s\n", price);
} else {
printf("No match found\n");
}
regfree(®ex);
return 0;
}
この例では、テキスト内の価格($99.99)をマッチングするために正規表現を使用しています。まず、正規表現をコンパイルし、その後、regexec関数を使用してテキスト内でマッチングアイテムを検索します。マッチングアイテムが見つかった場合、価格をテキストから抽出して出力します。最後に、正規表現オブジェクトを解放します。
ご注意ください、これは単なる簡単な例であり、実際のテキストデータ抽出にはより複雑な正規表現と処理ロジックが必要となる場合があります。