検索と置換
キーボードとマウスを使用して文書内を簡単に移動できますが、スクロールするページが多い場合は、長い文書内の特定のテキストを見つけるのにかなり時間がかかります。 文書で使用した特定の文字や単語を置き換える場合は、時間がかかります。 “検索と置換"機能を使用すると、ドキュメント内の一連の文字を検索し、別の一連の文字に置き換えることができます。
Aspose.Wordsを使用すると、Microsoft Wordなどの追加のアプリケーションをインストールして使用することなく、文書内の特定の文字列または正規表現パターンを検索し、代替 これは、潜在的にあなたの仕事の時間を節約し、多くの入力と書式設定のタスクを高速化します。
この記事では、メタ文字をサポートして文字列置換と正規表現を適用する方法について説明します。
{#ways-to-find-and-replace}の検索と置換の方法
Aspose.Wordsは、次を使用して検索操作と置換操作を適用する2つの方法を提供します:
- Simple string replacement–特定の文字列を検索して別の文字列に置き換えるには、別の指定された置換文字列ですべての出現に応じて置換される検索文字列(英数字)を指定す 両方の文字列にシンボルを含めることはできません。 文字列の比較で大文字と小文字が区別される場合や、スペルがわからない場合や、いくつかの類似のスペルがある場合があることを考慮してくださ
- Regular expressions-正規表現を指定して、一致する文字列を正確に検索し、正規表現に従って置換します。 単語は英数字のみで構成されていると定義されていることに注意してください。 単語全体のみが一致して置換が実行され、入力文字列に記号が含まれている場合、フレーズは見つかりません。
さらに、特殊なメタ文字と単純な文字列置換および正規表現を使用して、検索および置換操作内で改行を指定することもできます。
Aspose.Wordsは、検索および置換機能をAspose.Words.Replacing名前空間に提示します。 FindReplaceOptionsクラスを使用して、検索および置換プロセス中に多くのオプションを操作できます。
単純な文字列置換{#find-and-replace-text-using-simple-string-replacement}を使用したテキストの検索と置換
Replaceメソッドのいずれかを使用して、特定の文字列を検索または置換し、行われた置換の数を返すことができます。 この場合、置換する文字列、すべての出現箇所を置換する文字列、置換で大文字と小文字が区別されるかどうか、およびスタンドアロンの単語のみが影響を受けるかどうかを指定できます。
次のコード例は、文字列”CustomerName“を見つけて文字列*“James Bond"に置き換える方法を示しています*:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// Load a Word Docx document by creating an instance of the Document class. | |
auto doc = System::MakeObject<Document>(); | |
auto builder = System::MakeObject<DocumentBuilder>(doc); | |
builder->Writeln(u"Hello _CustomerName_, "); | |
// Specify the search string and replace string using the Replace method. | |
doc->get_Range()->Replace(u"_CustomerName_", u"James Bond", System::MakeObject<FindReplaceOptions>()); | |
// Save the result. | |
System::String outputPath = outputDataDir + u"Range.ReplaceSimple.docx"; | |
doc->Save(outputPath); |
単純な文字列置換を適用する前に、ドキュメントの違いに気付くことができます:
単純な文字列置換を適用した後:
正規表現{#find-and-replace-text-using-regular-expressions}を使用したテキストの検索と置換
正規表現(regex)は、特定の一連のテキストを記述するパターンです。 単語のすべての二重出現を単一の単語の出現に置き換えたいとします。 次に、次の正規表現を適用してダブルワードパターンを指定できます:([a-zA-Z]+) \1
。
他のReplaceメソッドを使用して、Regex
パラメータを正規表現パターンとして設定して一致を見つけることにより、特定の文字の組み合わせを検索して置換します。
次のコード例は、正規表現パターンに一致する文字列を、指定された置換文字列に置き換える方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
auto builder = System::MakeObject<DocumentBuilder>(doc); | |
builder->Writeln(u"sad mad bad"); | |
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>(); | |
// Replaces all occurrences of the words "sad" or "mad" to "bad". | |
doc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"[s|m]ad"), u"bad", options); | |
const System::String outputPath = outputDataDir + u"FindAndReplaceWithRegex_out.doc"; | |
doc->Save(outputPath); |
正規表現で文字列置換を適用する前に、ドキュメントの違いに気付くことができます:
正規表現で文字列置換を適用した後:
メタ文字{#find-and-replace-text-using-metacharacters}を使用した文字列の検索と置換
特定のテキストまたは語句が複数の段落、セクション、またはページで構成されている場合は、検索文字列または置換文字列でメタ文字を使用できます。 メタ文字の中には、段落区切りの**&p**、セクション区切りの**&b**、改ページの**&m**、改行の**&l**などがあります。
次のコード例は、テキストを段落と改ページに置き換える方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
builder->get_Font()->set_Name(u"Arial"); | |
builder->Writeln(u"First section"); | |
builder->Writeln(u" 1st paragraph"); | |
builder->Writeln(u" 2nd paragraph"); | |
builder->Writeln(u"{insert-section}"); | |
builder->Writeln(u"Second section"); | |
builder->Writeln(u" 1st paragraph"); | |
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>(); | |
options->get_ApplyParagraphFormat()->set_Alignment(ParagraphAlignment::Center); | |
// Double each paragraph break after word "section", add kind of underline and make it centered. | |
int32_t count = doc->get_Range()->Replace(u"section&p", u"section&p----------------------&p", options); | |
// Insert section break instead of custom text tag. | |
count = doc->get_Range()->Replace(u"{insert-section}", u"&b", options); | |
System::String savePath = outputDataDir + u"FindReplaceUsingMetaCharacters.ReplaceTextContaingMetaCharacters.docx"; | |
doc->Save(savePath); |
文書{#find-and-replace-string-in-header-or-footer-of-a-document}のヘッダ/フッタ内の文字列の検索と置換
HeaderFooterクラスを使用して、Word文書のヘッダー/フッターセクションでテキストを検索して置き換えることができます。
次のコード例は、ドキュメント内のヘッダーセクションのテキストを置き換える方法を示しています:
ヘッダー文字列の置換を適用する前に、ドキュメントの違いに気付くことができます:
ヘッダー文字列置換を適用した後:
ドキュメント内のフッターセクションのテキストを置き換えるコード例は、前のヘッダーコード例と非常によく似ています。 あなたがする必要があるのは、次の2つの行を置き換えることだけです:
auto header = headersFooters->idx_get(HeaderFooterType::HeaderPrimary);
header->get_Range()->Replace(u"Aspose.Words", u"Remove", options);
以下のようにして:
auto footer = headersFooters->idx_get(HeaderFooterType::FooterPrimary);
footer->get_Range()->Replace(u"(C) 2006 Aspose Pty Ltd.", u"Copyright (C) Aspose Pty Ltd.", options);
フッター文字列置換を適用する前に、ドキュメントの違いに気付くことができます:
フッター文字列置換を適用した後:
検索中にテキストを無視して{#ignore-text-during-find-and-replace}を置換する
検索と置換操作を適用している間は、テキストの特定のセグメントを無視できます。 したがって、テキストの特定の部分を検索から除外することができ、検索と置換は残りの部分にのみ適用できます。
Aspose.Wordsは、次のようなテキストを無視するための多くの検索および置換プロパティを提供しますIgnoreDeleted, IgnoreFieldCodes, IgnoreFields, IgnoreFootnotes, とIgnoreInserted。
次のコード例は、delete revisions内のテキストを無視する方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
// Insert non-revised text. | |
builder->Writeln(u"Deleted"); | |
builder->Write(u"Text"); | |
// Remove first paragraph with tracking revisions. | |
doc->StartTrackRevisions(u"John Doe", System::DateTime::get_Now()); | |
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->Remove(); | |
doc->StopTrackRevisions(); | |
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>(); | |
// Replace 'e' in document while deleted text. | |
options->set_IgnoreDeleted(true); | |
doc->get_Range()->Replace(System::MakeObject<Regex>(u"e"), u"*", options); | |
std::cout << doc->GetText().ToUtf8String() << std::endl; // The output is: Deleted\rT*xt\f | |
// Replace 'e' in document NOT ignoring deleted text. | |
options->set_IgnoreDeleted(false); | |
doc->get_Range()->Replace(System::MakeObject<Regex>(u"e"), u"*", options); | |
std::cout << doc->GetText().ToUtf8String() << std::endl; // The output is: D*l*t*d\rT*xt\f |
検索と置換操作のカスタマイズ
Aspose.Wordsは、ApplyFontとApplyParagraphFormatsプロパティで特定の形式を適用する、UseSubstitutionsプロパティで置換パターンで置換を使用するなど、テキストを検索して置換するための多くの異なるpropertiesを提供します。
次のコード例は、ドキュメント内の特定の単語を強調表示する方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// Highlight word "the" with yellow color. | |
auto options = System::MakeObject<FindReplaceOptions>(); | |
options->get_ApplyFont()->set_HighlightColor(System::Drawing::Color::get_Yellow()); | |
// Replace highlighted text. | |
doc->get_Range()->Replace(u"Hello", u"Hello", options); |
Aspose.WordsIReplacingCallbackインターフェイスを使用して、置換操作中にカスタムメソッドを作成して呼び出すことができます。 正規表現で指定されたテキストをHTMLタグで置き換えるなど、検索と置換操作をカスタマイズする必要があるユースケースがあるかもしれませんので、基本的にはhtmlを挿入して置換を適用します。
文字列をHTMLタグに置き換える必要がある場合は、IReplacingCallbackインターフェイスを適用して検索と置換操作をカスタマイズし、文書のmatchノードで実行の開始時に一致が開始されるようにします。 IReplacingCallbackを使用するいくつかの例を提供しましょう。
次のコード例は、指定されたテキストをHTMLに置き換える方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
class ReplaceWithHtmlEvaluator : public IReplacingCallback | |
{ | |
typedef ReplaceWithHtmlEvaluator ThisType; | |
typedef IReplacingCallback BaseType; | |
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo; | |
RTTI_INFO(ThisType, ThisTypeBaseTypesInfo); | |
public: | |
ReplaceWithHtmlEvaluator(System::SharedPtr<FindReplaceOptions> options); | |
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> args) override; | |
private: | |
System::SharedPtr<FindReplaceOptions> mOptions; | |
}; | |
ReplaceWithHtmlEvaluator::ReplaceWithHtmlEvaluator(System::SharedPtr<FindReplaceOptions> options) | |
{ | |
mOptions = options; | |
} | |
ReplaceAction ReplaceWithHtmlEvaluator::Replacing(System::SharedPtr<ReplacingArgs> args) | |
{ | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(System::DynamicCast<Document>(args->get_MatchNode()->get_Document())); | |
builder->MoveTo(args->get_MatchNode()); | |
// Replace '<CustomerName>' text with a red bold name. | |
builder->InsertHtml(u"<b><font color='red'>James Bond, </font></b>"); | |
args->set_Replacement(u""); | |
return ReplaceAction::Replace; | |
} | |
void ReplaceWithHtml(System::String const& inputDataDir, System::String const& outputDataDir) | |
{ | |
auto doc = System::MakeObject<Document>(); | |
auto builder = System::MakeObject<DocumentBuilder>(doc); | |
builder->Writeln(u"Hello <CustomerName>,"); | |
auto options = System::MakeObject<FindReplaceOptions>(); | |
auto optionsReplacingCallback = System::MakeObject<ReplaceWithHtmlEvaluator>(options); | |
doc->get_Range()->Replace(new Regex(u" <CustomerName>,"), System::String::Empty, options); | |
// Save the modified document. | |
doc->Save(outputDataDir + u"Range.ReplaceWithInsertHtml.doc"); | |
} |
次のコード例は、緑の色で正の数を強調表示し、赤の色で負の数を強調表示する方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// Replace and Highlight Numbers. | |
class NumberHighlightCallback : public IReplacingCallback | |
{ | |
typedef NumberHighlightCallback ThisType; | |
typedef IReplacingCallback BaseType; | |
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo; | |
RTTI_INFO(ThisType, ThisTypeBaseTypesInfo); | |
public: | |
NumberHighlightCallback(System::SharedPtr<FindReplaceOptions> const& opt) | |
: mOpt(opt) { } | |
Aspose::Words::Replacing::ReplaceAction Replacing(System::SharedPtr<Aspose::Words::Replacing::ReplacingArgs> args) override | |
{ | |
// Let replacement to be the same text. | |
args->set_Replacement(args->get_Match()->get_Value()); | |
auto val = System::Convert::ToInt32(args->get_Match()->get_Value()); | |
// Apply either red or green color depending on the number value sign. | |
mOpt->get_ApplyFont()->set_Color(val > 0 ? System::Drawing::Color::get_Green() : System::Drawing::Color::get_Red()); | |
return ReplaceAction::Replace; | |
} | |
private: | |
System::SharedPtr<FindReplaceOptions> mOpt; | |
}; |
次のコード例は、各行の先頭に行番号を追加する方法を示しています:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
class LineCounterCallback : public IReplacingCallback | |
{ | |
typedef LineCounterCallback ThisType; | |
typedef IReplacingCallback BaseType; | |
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo; | |
RTTI_INFO(ThisType, ThisTypeBaseTypesInfo); | |
public: | |
Aspose::Words::Replacing::ReplaceAction Replacing(System::SharedPtr<Aspose::Words::Replacing::ReplacingArgs> args) override | |
{ | |
std::cout << args->get_Match()->get_Value().ToUtf8String() << '\n'; | |
args->set_Replacement(System::String::Format(u"{0} {1}", mCounter++, args->get_Match()->get_Value())); | |
return ReplaceAction::Replace; | |
} | |
private: | |
int32_t mCounter = 1; | |
}; | |
void LineCounter(System::String const& inputDataDir, System::String const& outputDataDir) | |
{ | |
// Create a document. | |
auto doc = System::MakeObject<Document>(); | |
auto builder = System::MakeObject<DocumentBuilder>(doc); | |
// Add lines of text. | |
builder->Writeln(u"This is first line"); | |
builder->Writeln(u"Second line"); | |
builder->Writeln(u"And last line"); | |
// Prepend each line with line number. | |
auto opt = System::MakeObject<FindReplaceOptions>(); | |
opt->set_ReplacingCallback(System::MakeObject<LineCounterCallback>()); | |
doc->get_Range()->Replace(System::MakeObject<Regex>(u"[^&p]*&p"), u"", opt); | |
doc->Save(outputDataDir + u"TestLineCounter.docx"); | |
} |