מצא והחלפת
אתה יכול לנווט בקלות במסמך שלך באמצעות מקלדת ועכבר, אבל אם יש לך דפים רבים לגלול דרך, זה ייקח די הרבה זמן כדי למצוא טקסט מסוים במסמך ארוך. זה יהיה יותר זמן לצרוך כאשר אתה רוצה להחליף דמויות או מילים מסוימות שהשתמשת במסמך שלך. פונקציונליות “מצא והחלפת” מאפשרת לך למצוא רצף של דמויות במסמך ולהחליף אותו עם רצף אחר של דמויות.
Aspose.Words מאפשר לך למצוא תבנית מחרוזת מסוימת או ביטוי קבוע במסמך שלך ולהחליף אותו עם אלטרנטיבה ללא התקנה ושימוש יישומים נוספים כגון: Microsoft Word. זה יזרז משימות הקלדה ופורמטיביות רבות, שעלולות לחסוך שעות עבודה.
מאמר זה מסביר כיצד ליישם החלפת מיתר וביטויים קבועים עם התמיכה של metacharacters.
דרכים למצוא ולחליף
Aspose.Words מספק שתי דרכים ליישם את החיפוש ולהחליף את הפעולה באמצעות הפעולות הבאות:
1.1 1. * החלפת מחרוזת פשוטה* - כדי למצוא ולהחליף מחרוזת מסוימת עם אחר, אתה צריך לציין מחרוזת חיפוש (דמויות אלפרמריות) אשר תוחלף על פי כל האירועים עם מחרוזת חלופית נוספת. שני המיתרים לא חייבים להכיל סמלים. קח בחשבון כי השוואה מחרוזת יכול להיות רגיש במקרה, או שאתה יכול להיות לא בטוח לחשים או יש כמה לחשים דומים. 2. * ביטויים רשומים* – כדי לציין ביטוי קבוע למציאת משחקי המחרוזת המדויקים ולהחליפם בהתאם לביטוי הרגיל שלך. שים לב שמילה מוגדרת כמרכיבים רק דמויות אלפאמריות. אם החלפת מבוצעת עם רק מילים שלמות תואמות ומחרוזת קלט מתרחשת להכיל סמלים, אז לא יימצאו ביטויים.
כמו כן, אתה יכול להשתמש metacharacters מיוחדים עם תחליף מחרוזת פשוט ביטויים קבועים כדי לציין הפסקות בתוך מוצא להחליף את המבצע.
Aspose.Words מציג את הפונקציונליות וההחלפה עם IReplacingCallBack. אתה יכול לעבוד עם אפשרויות רבות במהלך למצוא ולהחליף את התהליך באמצעות 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-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"); |
ניתן להבחין בין המסמך לפני החלת החלפת מחרוזת פשוטה:

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

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

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

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-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"); |
Find and Replace String in Header/Footer of a Document
אתה יכול למצוא ולהחליף טקסט בחלק ראש / מ"ר של מסמך Word באמצעות מסמך Word באמצעות HeaderFooter מעמד.
הדוגמה הבאה של הקוד מראה כיצד להחליף את הטקסט של החלק הראשי במסמך שלך:
// 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"); |
ניתן להבחין בין המסמך לפני החלת החלפת מיתר ראש:

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

לדוגמה הקוד להחליף את הטקסט של סעיף ה- Footer במסמך שלך דומה מאוד לדוגמה הקודמת קוד ראשי. כל שעליך לעשות הוא להחליף את שני השורות הבאות:
HeaderFooter header = headersFooters.get(HeaderFooterType.HEADER_PRIMARY);
header.getRange().replace("Aspose.Words", "Remove", options);
עם הדברים הבאים:
אתה יכול להבחין ההבדל בין המסמך לפני החלת החלפת מיתר רגל:

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

עקבו אחרי Find and Replace
בעת החלת פעולת המוצא וההחלפה, אתה יכול להתעלם מקטעים מסוימים של הטקסט. לכן, חלקים מסוימים של הטקסט ניתן לשלול מן החיפוש, ואת הממצאים וההחלפה ניתן ליישם רק את החלקים הנותרים.
Aspose.Words מספק תכונות רבות להתעלמות מטקסט כגון IgnoreDeleted, IgnoreFieldCodes, IgnoreFields, IgnoreFootnotes, ו IgnoreInserted.
הדוגמה הבאה של הקוד מראה כיצד להתעלם טקסט בתוך הסרת תיקונים:
// 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 |
עקבו אחרי Find and Replace Operation
Aspose.Words מספק הרבה שונה properties למצוא ולהחליף טקסט כגון יישום פורמט ספציפי עם ApplyFont ו ApplyParagraphFormats תכונות, באמצעות החלפת דפוסים חלופיים UseSubstitutions רכוש, ואחרים.
לדוגמה הקוד הבא מראה כיצד להדגיש מילה מסוימת במסמך שלך:
// 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 ממשק כדי להתאים אישית את מציאת והחלפת הפעולה כך המשחק מתחיל בתחילת ריצה עם צומת המשחק של המסמך שלך. תן לנו לספק כמה דוגמאות לשימוש 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; | |
} | |
} |