מצא והחלפת
אתה יכול לנווט בקלות במסמך שלך באמצעות מקלדת ועכבר, אבל אם יש לך דפים רבים לגלול דרך, זה ייקח די הרבה זמן כדי למצוא טקסט מסוים במסמך ארוך. זה יהיה יותר זמן לצרוך כאשר אתה רוצה להחליף דמויות או מילים מסוימות שהשתמשת במסמך שלך. פונקציונליות “מצא והחלפת” מאפשרת לך למצוא רצף של דמויות במסמך ולהחליף אותו עם רצף אחר של דמויות.
Aspose.Words מאפשר לך למצוא תבנית מחרוזת מסוימת או ביטוי קבוע במסמך שלך ולהחליף אותו עם אלטרנטיבה ללא התקנה ושימוש יישומים נוספים כגון: Microsoft Word. זה יזרז משימות הקלדה ופורמטיביות רבות, שעלולות לחסוך שעות עבודה.
מאמר זה מסביר כיצד ליישם החלפת מיתר וביטויים קבועים עם התמיכה של metacharacters.
דרכים למצוא ולחליף
Aspose.Words מספק שתי דרכים ליישם את החיפוש ולהחליף את הפעולה באמצעות הפעולות הבאות:
1.1 1. * החלפת מחרוזת פשוטה* - כדי למצוא ולהחליף מחרוזת מסוימת עם אחר, אתה צריך לציין מחרוזת חיפוש (דמויות אלפרמריות) אשר תוחלף על פי כל האירועים עם מיתר חלופי מוגדר אחר. שני המיתרים לא חייבים להכיל סמלים. קח בחשבון כי השוואה מחרוזת יכול להיות רגיש במקרה, או שאתה יכול להיות לא בטוח לחש או יש כמה לחשים דומים. 2. * ביטויים רשומים* - כדי לציין ביטוי קבוע למציאת משחקי המחרוזת המדויקים ולהחליפם על פי הביטוי הרגיל שלך. שים לב שמילה מוגדרת כמרכיבים רק דמויות אלפאמריות. אם החלפתם מבוצעת עם רק מילים שלמות תואמות ומחרוזת קלט מתרחשת להכיל סמלים, אז לא יימצאו ביטויים.
בנוסף, אתה יכול להשתמש metacharacters מיוחדים עם החלפת מחרוזת פשוטה וביטויים קבועים כדי לציין הפסקות בתוך מוצא והחלפת המבצע.
Aspose.Words מציג את הפונקציונליות וההחלפה עם Aspose.Words.Replacing שם. אתה יכול לעבוד עם אפשרויות רבות במהלך למצוא ולהחליף את התהליך באמצעות FindReplaceOptions מעמד.
Find and Replace Text Using Simple String
אתה יכול להשתמש באחד Replace שיטות למצוא או להחליף מחרוזת מסוימת ולהחזיר את מספר ההחלפה שנעשו. במקרה זה, אתה יכול לציין מחרוזת שיש להחליף, מחרוזת שתחליף את כל האירועים שלה, בין אם ההחלפה היא רגישה במקרה, ואם רק מילים עומדות-אלון יושפעו.
הדוגמה הקודית הבאה מראה כיצד למצוא את המיתרים “Customername” ולהחליף אותו עם המחרוזת “ג’יימס בונד”:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// 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.Range.Replace("_CustomerName_", "James Bond", new FindReplaceOptions()); | |
// Save the result. | |
doc.Save(dataDir + "Range.ReplaceSimple.docx"); |
ניתן להבחין בין המסמך לפני החלת החלפת מיתר פשוטה:

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

מצא והחלפת טקסט באמצעות ביטויים רגילים
ביטוי קבוע (regex) הוא דפוס המתאר רצף מסוים של טקסט. נניח שאתה רוצה להחליף את כל האירועים הכפולים של מילה עם התרחשות מילה אחת. לאחר מכן תוכל ליישם את הביטוי הרגיל הבא כדי לציין את תבנית המילה הכפולה: ([a-zA-Z]+) \1
.
השתמש באחר Replace שיטה לחיפוש ולהחלפת שילובי אופי ספציפיים על ידי הגדרת Regex
פרמטר כתבנית ביטוי רגילה למציאת משחקים.
הדוגמה הבאה של הקוד מראה כיצד להחליף מיתרים שמתאימים לתבנית ביטוי רגילה עם מיתר חלופי מוגדר:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.Writeln("sad mad bad"); | |
Assert.AreEqual("sad mad bad", doc.GetText().Trim()); | |
// Replaces all occurrences of the words "sad" or "mad" to "bad". | |
doc.Range.Replace(new Regex("[s|m]ad"), "bad"); | |
// Save the Word document. | |
doc.Save("Range.ReplaceWithRegex.docx"); |
אתה יכול להבחין בין המסמך לפני החלת החלפת מיתר עם ביטויים קבועים:

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

Find and Replace String Using Metacharacters
אתה יכול להשתמש metacharacters במחרוזת החיפוש או מחרוזת החלפת אם טקסט מסוים או ביטוי מורכב פסקאות מרובות, חלקים או דפים. חלק מהמטגנים כוללים &p על הפסקה, &b עבור הפסקה, &m עבור דף נשבר, &l בשביל הפסקה קו.
הדוגמה הבאה של הקוד מראה כיצד להחליף טקסט עם פסקה ושבר דף:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.Font.Name = "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.ApplyParagraphFormat.Alignment = ParagraphAlignment.Center; | |
// Double each paragraph break after word "section", add kind of underline and make it centered. | |
int count = doc.Range.Replace("section&p", "section&p----------------------&p", options); | |
// Insert section break instead of custom text tag. | |
count = doc.Range.Replace("{insert-section}", "&b", options); | |
dataDir = dataDir + "ReplaceTextContaingMetaCharacters_out.docx"; | |
doc.Save(dataDir); |
Find and Replace String in Header/Footer of a Document
אתה יכול למצוא ולהחליף טקסט בחלק ראש / מ"ר של מסמך Word באמצעות מסמך Word באמצעות HeaderFooter מעמד.
הדוגמה הבאה של הקוד מראה כיצד להחליף את הטקסט של הקטע הראשי במסמך שלך:
ניתן להבחין בין המסמך לפני החלת החלפת מיתר ראש:

לאחר יישום החלפת כותרות:

דוגמא הקוד להחליף את הטקסט של סעיף ה- Footer במסמך שלך דומה מאוד לדוגמה הקודמת קוד ראשי. כל שעליך לעשות הוא להחליף את שני השורות הבאות:
HeaderFooter header = headersFooters[HeaderFooterType.HeaderPrimary];
header.Range.Replace("Aspose.Words", "Remove", options);
עם הדברים הבאים:
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];
int currentYear = System.DateTime.Now.Year;
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", $"Copyright (C) {currentYear} by Aspose Pty Ltd.", options);
אתה יכול להבחין ההבדל בין המסמך לפני החלת החלפת מיתר רגל:

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

עקבו אחרי Find and Replace
בעת החלת פעולת המוצא וההחלפה, אתה יכול להתעלם מקטעים מסוימים של הטקסט. לכן, חלקים מסוימים של הטקסט ניתן לשלול מן החיפוש, ואת הממצאים וההחלפה ניתן ליישם רק את החלקים הנותרים.
Aspose.Words מספק תכונות רבות להתעלמות מטקסט כגון IgnoreDeleted, IgnoreFieldCodes, IgnoreFields, IgnoreFootnotes, ו IgnoreInserted.
הדוגמה הבאה של הקוד מראה כיצד להתעלם טקסט בתוך הסרת תיקונים:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
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("John Doe", DateTime.Now); | |
doc.FirstSection.Body.FirstParagraph.Remove(); | |
doc.StopTrackRevisions(); | |
Regex regex = new Regex("e"); | |
FindReplaceOptions options = new FindReplaceOptions(); | |
// Replace 'e' in document while ignoring deleted text. | |
options.IgnoreDeleted = true; | |
doc.Range.Replace(regex, "*", options); | |
Assert.AreEqual(doc.GetText().Trim(), "Deleted\rT*xt"); | |
// Replace 'e' in document while not ignoring deleted text. | |
options.IgnoreDeleted = false; | |
doc.Range.Replace(regex, "*", options); |
עקבו אחרי Find and Replace
Aspose.Words מספק הרבה שונה properties למצוא ולהחליף טקסט כגון יישום פורמט ספציפי עם ApplyFont ו ApplyParagraphFormats תכונות, באמצעות החלפת דפוסים חלופיים UseSubstitutions רכוש, ואחרים.
לדוגמה הקוד הבא מראה כיצד להדגיש מילה מסוימת במסמך שלך:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// Highlight word "the" with yellow color. | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.ApplyFont.HighlightColor = Color.Yellow; | |
// Replace highlighted text. | |
doc.Range.Replace("Hello", "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-.NET | |
public static void ReplaceWithHtml(string dataDir) | |
{ | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.Writeln("Hello <CustomerName>,"); | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options); | |
doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options); | |
// Save the modified document. | |
doc.Save(dataDir + "Range.ReplaceWithInsertHtml.doc"); | |
} | |
private class ReplaceWithHtmlEvaluator : IReplacingCallback | |
{ | |
internal ReplaceWithHtmlEvaluator(FindReplaceOptions options) | |
{ | |
mOptions = options; | |
} | |
//This simplistic method will only work well when the match starts at the beginning of a run. | |
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args) | |
{ | |
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document); | |
builder.MoveTo(args.MatchNode); | |
// Replace '<CustomerName>' text with a red bold name. | |
builder.InsertHtml("<b><font color='red'>James Bond, </font></b>"); args.Replacement = ""; | |
return ReplaceAction.Replace; | |
} | |
private readonly FindReplaceOptions mOptions; | |
} |
לדוגמה הקוד הבא מראה כיצד להדגיש מספרים חיוביים עם צבע ירוק ומספרים שליליים עם צבע אדום:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// Replace and Highlight Numbers. | |
internal class NumberHighlightCallback : IReplacingCallback | |
{ | |
public NumberHighlightCallback(FindReplaceOptions opt) | |
{ | |
mOpt = opt; | |
} | |
public ReplaceAction Replacing(ReplacingArgs args) | |
{ | |
// Let replacement to be the same text. | |
args.Replacement = args.Match.Value; | |
int val = int.Parse(args.Match.Value); | |
// Apply either red or green color depending on the number value sign. | |
mOpt.ApplyFont.Color = (val > 0) | |
? Color.Green | |
: Color.Red; | |
return ReplaceAction.Replace; | |
} | |
private readonly FindReplaceOptions mOpt; | |
} |
הדוגמה הבאה של הקוד מראה כיצד להעביר מספר קו לכל קו:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
public void LineCounter() | |
{ | |
// 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() { ReplacingCallback = new LineCounterCallback() }; | |
doc.Range.Replace(new Regex("[^&p]*&p"), "", opt); | |
doc.Save(@"X:\TestLineCounter.docx"); | |
} | |
internal class LineCounterCallback : IReplacingCallback | |
{ | |
public ReplaceAction Replacing(ReplacingArgs args) | |
{ | |
Debug.WriteLine(args.Match.Value); | |
args.Replacement = string.Format("{0} {1}", mCounter++, args.Match.Value); | |
return ReplaceAction.Replace; | |
} | |
private int mCounter = 1; | |
} |