מצא והחלף

אתה יכול לנווט בקלות בתוך המסמך שלך באמצעות מקלדת ועכבר, אך אם יש לך דפים רבים לגלול בהם, ייקח לא מעט זמן למצוא טקסט ספציפי במסמך ארוך. זה ייקח יותר זמן כשתרצה להחליף תווים או מילים מסוימים שבהם השתמשת במסמך שלך. הפונקציונליות “מצא והחלף” מאפשרת לך למצוא רצף של תווים במסמך ולהחליף אותו ברצף אחר של תווים.

Aspose.Words מאפשר לך למצוא מחרוזת ספציפית או דפוס ביטוי רגיל במסמך שלך ולהחליף אותו בחלופה מבלי להתקין ולהשתמש ביישומים נוספים כגון Microsoft Word. זה יאיץ משימות הקלדה ועיצוב רבות, מה שעלול לחסוך לך שעות עבודה.

מאמר זה מסביר כיצד ליישם החלפת מחרוזות וביטויים רגולריים בתמיכת מטא-תווים.

דרכים למצוא ולהחליף

Aspose.Words מספק שתי דרכים ליישם את פעולת החיפוש והחלפה באמצעות:

  1. Simple string replacement - כדי למצוא ולהחליף מחרוזת ספציפית במחרוזת אחרת, עליך לציין מחרוזת חיפוש (תווים אלפאנומריים) שתוחלף בהתאם לכל המופעים במחרוזת החלפה אחרת שצוינה. אסור ששני המיתרים יכילו סמלים. קח בחשבון שהשוואת מחרוזות יכולה להיות תלוית רישיות, או שאתה לא בטוח באיות או שיש לך כמה איותים דומים.
  2. Regular expressions - כדי לציין ביטוי רגולרי כדי למצוא את התאמת המחרוזת המדויקת ולהחליף אותם בהתאם לביטוי הרגולרי שלך. שים לב שמילה מוגדרת כמורכבת מאותיות אלפאנומריות בלבד. אם החלפה מבוצעת עם רק מילים שלמות שמתאימות ומחרוזת הקלט מכילה במקרה סמלים, אז לא יימצאו ביטויים.

בנוסף, ניתן להשתמש במטא-תווים מיוחדים עם החלפת מחרוזת פשוטה וביטויים רגולריים כדי לציין הפסקות בתוך פעולת החיפוש והחלפה.

Aspose.Words מציג את הפונקציונליות חיפוש והחלפה במרחב השמות Aspose.Words.Replacing. אתה יכול לעבוד עם אפשרויות רבות במהלך תהליך החיפוש והחלפה באמצעות מחלקה FindReplaceOptions.

מצא והחלף טקסט באמצעות החלפת מחרוזת פשוטה

באפשרותך להשתמש באחת מהשיטות 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);

אתה יכול להבחין בהבדל בין המסמך לפני החלת החלפת מחרוזת פשוטה:

before-simple-string-replacement-aspose-words-cpp

ולאחר החלת החלפת מחרוזת פשוטה:

after-simple-string-replacement-aspose-words-cpp

חיפוש והחלפת טקסט באמצעות ביטויים רגולריים

ביטוי רגולרי (רגקס) הוא דפוס המתאר רצף מסוים של טקסט. נניח שאתה רוצה להחליף את כל המופעים הכפולים של מילה עם התרחשות מילה אחת. לאחר מכן תוכל להחיל את הביטוי הרגיל הבא כדי לציין את תבנית המילה הכפולה: ([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);

אתה יכול להבחין בהבדל בין המסמך לפני החלת החלפת מחרוזת בביטויים רגולריים:

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

ולאחר החלת החלפת מחרוזת עם ביטויים רגולריים:

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

מצא והחלף מחרוזת באמצעות מטא-תווים

אתה יכול להשתמש בתווים מטא במחרוזת החיפוש או במחרוזת ההחלפה אם טקסט או ביטוי מסוים מורכבים ממספר פסקאות, קטעים או עמודים. חלק מטא-תווים כוללים &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);

אתה יכול למצוא ולהחליף טקסט בקטע כותרת עליונה / תחתונה במסמך Word באמצעות הכיתה HeaderFooter.

דוגמת הקוד הבאה מראה כיצד להחליף את הטקסט של קטע הכותרת במסמך שלך:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open the template document, containing obsolete copyright information in the footer.
auto doc = System::MakeObject<Document>(inputDataDir + u"HeaderFooter.ReplaceText.doc");
// Access header of the Word document.
auto headersFooters = doc->get_FirstSection()->get_HeadersFooters();
auto header = headersFooters->idx_get(HeaderFooterType::HeaderPrimary);
// Set options.
auto options = System::MakeObject<FindReplaceOptions>();
options->set_MatchCase(false);
options->set_FindWholeWordsOnly(false);
// Replace text in the header of the Word document.
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);
// Save the Word document.
doc->Save(outputDataDir + u"HeaderReplace.docx");

אתה יכול להבחין בהבדל בין המסמך לפני החלת החלפת מחרוזת כותרת:

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

ולאחר החלת החלפת מחרוזת כותרת:

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

דוגמת הקוד להחלפת הטקסט של קטע הכותרת התחתונה במסמך שלך דומה מאוד לדוגמא קוד הכותרת הקודמת. כל שעליך לעשות הוא להחליף את שתי השורות הבאות:

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);

אתה יכול להבחין בהבדל בין המסמך לפני החלת החלפת מחרוזת תחתונה:

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

ולאחר החלת החלפת מחרוזת תחתונה:

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

התעלם מטקסט במהלך חיפוש והחלפה

בעת החלת פעולת החיפוש והחלפה, תוכל להתעלם מקטעים מסוימים בטקסט. לכן, חלקים מסוימים של הטקסט ניתן להוציא מן החיפוש, ואת למצוא ולהחליף ניתן להחיל רק על החלקים הנותרים.

Aspose.Words מספק תכונות חיפוש והחלפה רבות להתעלמות מטקסט כגון IgnoreDeleted, IgnoreFieldCodes, IgnoreFields, IgnoreFootnotes, ו - IgnoreInserted.

דוגמת הקוד הבאה מראה כיצד להתעלם מטקסט בתוך מחיקת תיקונים:

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 מספק הרבה properties שונים כדי למצוא ולהחליף טקסט כגון החלת פורמט ספציפי עם ApplyFont ו ApplyParagraphFormats מאפיינים, באמצעות החלפות בדפוסי החלפה עם UseSubstitutions נכס, ואחרים.

דוגמת הקוד הבאה מראה כיצד להדגיש מילה ספציפית במסמך שלך:

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.Words מאפשר לך להשתמש IReplacingCallback ממשק כדי ליצור ולקרוא שיטה מותאמת אישית במהלך פעולת החלפה. ייתכן שיש לך כמה מקרי שימוש שבהם עליך להתאים אישית את פעולת החיפוש והחלפה, כגון החלפת טקסט שצוין בביטוי רגולרי בתגים HTML, כך שבעצם תחיל החלפה בהכנסה HTML.

אם עליך להחליף מחרוזת בתג HTML, החל את ממשק IReplacingCallback כדי להתאים אישית את פעולת החיפוש והחלפה כך שההתאמה תתחיל בתחילת הריצה עם צומת ההתאמה של המסמך שלך. תן לנו לספק כמה דוגמאות לשימוש 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");
}