検索と置換

キーボードとマウスを使用して文書内を簡単に移動できますが、スクロールするページが多い場合は、長い文書内の特定のテキストを見つけるのにかなり時間がかかります。 文書で使用した特定の文字や単語を置き換える場合は、時間がかかります。 “検索と置換"機能を使用すると、ドキュメント内の一連の文字を検索し、別の一連の文字に置き換えることができます。

Aspose.Wordsを使用すると、Microsoft Wordなどの追加のアプリケーションをインストールして使用することなく、文書内の特定の文字列または正規表現パターンを検索し、代替 これは、潜在的にあなたの仕事の時間を節約し、多くの入力と書式設定のタスクを高速化します。

この記事では、メタ文字をサポートして文字列置換と正規表現を適用する方法について説明します。

{#ways-to-find-and-replace}の検索と置換の方法

Aspose.Wordsは、次を使用して検索操作と置換操作を適用する2つの方法を提供します:

  1. Simple string replacement–特定の文字列を検索して別の文字列に置き換えるには、別の指定された置換文字列ですべての出現に応じて置換される検索文字列(英数字)を指定す 両方の文字列にシンボルを含めることはできません。 文字列の比較で大文字と小文字が区別される場合や、スペルがわからない場合や、いくつかの類似のスペルがある場合があることを考慮してくださ
  2. Regular expressions-正規表現を指定して、一致する文字列を正確に検索し、正規表現に従って置換します。 単語は英数字のみで構成されていると定義されていることに注意してください。 単語全体のみが一致して置換が実行され、入力文字列に記号が含まれている場合、フレーズは見つかりません。

また、特殊なメタ文字と単純な文字列置換および正規表現を使用して、検索および置換操作内で改行を指定することもできます。

Aspose.Wordsは、検索および置換機能をIReplacingCallBackに示します。 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-Java
// Load a Word DOCX document by creating an instance of the Document class.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello _CustomerName_,");
// Specify the search string and replace string using the Replace method.
doc.getRange().replace("_CustomerName_", "James Bond", new FindReplaceOptions());
// Save the result.
doc.save(dataDir + "Range.ReplaceSimple.docx");

単純な文字列置換を適用する前に、ドキュメントの違いに気付くことができます:

before-simple-string-replacement-aspose-words-java

単純な文字列置換を適用した後:

after-simple-string-replacement-aspose-words-java

正規表現 {#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-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("sad mad bad");
if(doc.getText().trim() == "sad mad bad")
{
System.out.println("Strings are equal!");
}
// Replaces all occurrences of the words "sad" or "mad" to "bad".
FindReplaceOptions options = new FindReplaceOptions();
doc.getRange().replace(Pattern.compile("[s|m]ad"), "bad", options);
// Save the Word document.
doc.save(dataDir + "Range.ReplaceWithRegex.docx");

正規表現で文字列置換を適用する前に、ドキュメントの違いに気付くことができます:

before-replacement-with-regular-expressions-aspose-words-java

正規表現で文字列置換を適用した後:

after-replacement-with-regular-expressions-aspose-words-java

メタ文字 {#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-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getFont().setName("Arial");
builder.writeln("First section");
builder.writeln(" 1st paragraph");
builder.writeln(" 2nd paragraph");
builder.writeln("{insert-section}");
builder.writeln("Second section");
builder.writeln(" 1st paragraph");
FindReplaceOptions options = new FindReplaceOptions();
options.getApplyParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
// Double each paragraph break after word "section", add kind of underline and make it centered.
int count = doc.getRange().replace("section&p", "section&p----------------------&p", options);
// Insert section break instead of custom text tag.
count = doc.getRange().replace("{insert-section}", "&b", options);
doc.save(dataDir + "ReplaceTextContaingMetaCharacters_out.docx");

HeaderFooterクラスを使用して、Word文書のヘッダー/フッターセクションでテキストを検索して置き換えることができます。

次のコード例は、ドキュメント内のヘッダーセクションのテキストを置き換える方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(dataDir + "HeaderFooter.ReplaceText.doc");
// Access header of the Word document.
HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters();
HeaderFooter header = headersFooters.get(HeaderFooterType.HEADER_PRIMARY);
// Set options.
FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
options.setFindWholeWordsOnly(false);
// Replace text in the header of the Word document.
header.getRange().replace("Aspose.Words", "Remove", options);
// Save the Word document.
doc.save(dataDir + "HeaderReplace.docx");

ヘッダー文字列の置換を適用する前に、ドキュメントの違いに気付くことができます:

before-applying-header-string-replacement-aspose-words-java

ヘッダー文字列置換を適用した後:

after-applying-header-string-replacement-aspose-words-java

ドキュメント内のフッターセクションのテキストを置き換えるコード例は、前のヘッダーコード例と非常によく似ています。 あなたがする必要があるのは、次の2つの行を置き換えることだけです:

HeaderFooter header = headersFooters.get(HeaderFooterType.HEADER_PRIMARY);
header.getRange().replace("Aspose.Words", "Remove", options);

以下のようにして:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters();
HeaderFooter footer = headersFooters.get(HeaderFooterType.FOOTER_PRIMARY);
// Replace text in the footer of the Word document.
int year = Calendar.getInstance().get(Calendar.YEAR);
footer.getRange().replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) " + year + " by Aspose Pty Ltd.", options);

フッター文字列置換を適用する前に、ドキュメントの違いに気付くことができます:

before-applying-footer-string-replacement-aspose-words-java

フッター文字列置換を適用した後:

after-applying-footer-string-replacement-aspose-words-java

検索中にテキストを無視して {#ignore-text-during-find-and-replace}を置換する

検索と置換操作を適用している間は、テキストの特定のセグメントを無視できます。 したがって、テキストの特定の部分を検索から除外することができ、検索と置換は残りの部分にのみ適用できます。

Aspose.Wordsは、次のようなテキストを無視するための多くの検索および置換プロパティを提供しますIgnoreDeleted, IgnoreFieldCodes, IgnoreFields, IgnoreFootnotes, とIgnoreInserted

次のコード例は、delete revisions内のテキストを無視する方法を示しています:

// Create new document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert non-revised text.
builder.writeln("Deleted");
builder.write("Text");
// Remove first paragraph with tracking revisions.
doc.startTrackRevisions("author", new Date());
doc.getFirstSection().getBody().getFirstParagraph().remove();
doc.stopTrackRevisions();
Pattern regex = Pattern.compile("e", Pattern.CASE_INSENSITIVE);
FindReplaceOptions options = new FindReplaceOptions();
// Replace 'e' in document ignoring deleted text.
options.setIgnoreDeleted(true);
doc.getRange().replace(regex, "*", options);
System.out.println(doc.getText()); // The output is: Deleted\rT*xt\f
// Replace 'e' in document NOT ignoring deleted text.
options.setIgnoreDeleted(false);
doc.getRange().replace(regex, "*", options);
System.out.println(doc.getText()); // The output is: D*l*t*d\rT*xt\f

検索と置換操作のカスタマイズ

Aspose.Wordsは、ApplyFontApplyParagraphFormatsプロパティで特定の形式を適用する、UseSubstitutionsプロパティで置換パターンで置換を使用するなど、テキストを検索して置換するための多くの異なるpropertiesを提供します。

次のコード例は、ドキュメント内の特定の単語を強調表示する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Highlight word "the" with yellow color.
FindReplaceOptions options = new FindReplaceOptions();
options.getApplyFont().setHighlightColor(Color.YELLOW);
// Replace highlighted text.
doc.getRange().replace("the", "the", options);

Aspose.Wordsを使用すると、IReplacingCallbackインターフェイスを使用して、置換操作中にカスタムメソッドを作成して呼び出すことができます。 正規表現で指定されたテキストをHTMLタグで置き換えるなど、検索と置換操作をカスタマイズする必要があるユースケースがあるかもしれませんので、基本的にはHTMLを挿入して置換を適用します。

文字列をHTMLタグに置き換える必要がある場合は、IReplacingCallbackインターフェイスを適用して検索と置換操作をカスタマイズし、文書のmatchノードで実行の開始時に一致が開始されるようにします。 IReplacingCallbackを使用するいくつかの例を提供しましょう。

次のコード例は、指定されたテキストをHTMLに置き換える方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void ReplaceWithHtml() throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello <CustomerName>,");
FindReplaceOptions options = new FindReplaceOptions();
options.setReplacingCallback(new ReplaceWithHtmlEvaluator());
doc.getRange().replace(Pattern.compile(" <CustomerName>,"), "", options);
//doc.getRange().replace(" <CustomerName>,", html, options);
// Save the modified document.
doc.save(dataDir + "Range.ReplaceWithInsertHtml.doc");
System.out.println("\nText replaced with meta characters successfully.\nFile saved at " + dataDir);
}
static class ReplaceWithHtmlEvaluator implements IReplacingCallback {
public int replacing(ReplacingArgs e) throws Exception {
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.getMatchNode();
// create Document Buidler and insert MergeField
DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
builder.moveTo(currentNode);
// Replace '<CustomerName>' text with a red bold name.
builder.insertHtml("<b><font color='red'>James Bond, </font></b>");e.getReplacement();
currentNode.remove();
//Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction.SKIP;
}
}

次のコード例は、緑の色で正の数を強調表示し、赤の色で負の数を強調表示する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Replace and Highlight Numbers.
static class NumberHighlightCallback implements IReplacingCallback {
public int replacing (ReplacingArgs args) throws Exception {
Node currentNode = args.getMatchNode();
// Let replacement to be the same text.
args.setReplacement(currentNode.getText());
int val = currentNode.hashCode();
// Apply either red or green color depending on the number value sign.
FindReplaceOptions options = new FindReplaceOptions();
if(val > 0)
{
options.getApplyFont().setColor(Color.GREEN);
}
else
{
options.getApplyFont().setColor(Color.RED);
}
return ReplaceAction.REPLACE;
}
}

次のコード例は、各行の先頭に行番号を追加する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void TestLineCounter() throws Exception {
// Create a document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add lines of text.
builder.writeln("This is first line");
builder.writeln("Second line");
builder.writeln("And last line");
// Prepend each line with line number.
FindReplaceOptions opt = new FindReplaceOptions();
opt.setReplacingCallback(new LineCounterCallback());
doc.getRange().replace(Pattern.compile("[^&p]*&p"), "", opt);
doc.save(dataDir + "TestLineCounter.docx");
}
static class LineCounterCallback implements IReplacingCallback
{
private int mCounter = 1;
public int replacing(ReplacingArgs args) throws Exception {
Node currentNode = args.getMatchNode();
System.out.println(currentNode.getText());
args.setReplacement(mCounter++ +"."+ currentNode.getText());
return ReplaceAction.REPLACE;
}
}