Tìm và Thay thế
Bạn có thể dễ dàng điều hướng trong tài liệu của mình bằng bàn phím và chuột nhưng nếu bạn có nhiều trang để cuộn qua, nó sẽ mất khá lâu để tìm văn bản cụ thể trong một tài liệu dài. Sẽ mất nhiều thời gian hơn khi bạn muốn thay thế những ký tự hoặc từ cụ thể mà bạn đã sử dụng trong tài liệu của mình. Tính năng “Tìm và thay thế” cho phép bạn tìm một chuỗi ký tự trong tài liệu và thay thế nó bằng một chuỗi ký tự khác.
Aspose.Words cho phép bạn tìm một chuỗi cụ thể hoặc mô hình biểu thức chính quy trong tài liệu của bạn và thay thế nó bằng một sự thay thế khác mà không cần cài đặt và sử dụng các ứng dụng bổ sung như Microsoft Word. Điều này sẽ giúp tăng tốc các tác vụ gõ và định dạng, có thể tiết kiệm cho bạn hàng giờ công việc.
Bài viết này giải thích cách áp dụng các thay thế chuỗi và biểu thức chính quy với sự hỗ trợ của các ký tự siêu.
Các cách để tìm và thay thế
Aspose.Words cung cấp hai cách để thực hiện thao tác tìm và thay thế bằng cách sử dụng những điều sau đây:
- Thay thế chuỗi đơn giản – để tìm và thay thế một chuỗi cụ thể bằng một chuỗi khác, bạn cần chỉ định một chuỗi tìm kiếm (các ký tự chữ số và chữ cái) sẽ được thay thế theo tất cả các lần xuất hiện với một chuỗi thay thế được chỉ định. Cả hai chuỗi này đều không được chứa các ký hiệu. Hãy lưu ý rằng so sánh chuỗi có thể nhạy cảm với chữ hoa và chữ thường hoặc bạn có thể không chắc về chính tả hoặc có một số cách đánh vần tương tự.
- Biểu thức chính quy – để chỉ định một biểu thức chính quy để tìm kiếm các chuỗi khớp và thay thế chúng theo biểu thức chính quy của bạn. Chú ý rằng một từ được định nghĩa là chỉ bao gồm các ký tự chữ số và chữ cái. Nếu một sự thay thế được thực hiện với chỉ các từ nguyên bản trùng khớp và chuỗi đầu vào tình cờ chứa các ký hiệu, thì không có câu nào sẽ được tìm thấy.
Ngoài ra, bạn có thể sử dụng các ký tự đặc biệt với việc thay thế chuỗi đơn giản và biểu thức chính quy để chỉ định những khoảng dừng trong hoạt động tìm kiếm và thay thế.
Aspose.Words trình bày chức năng tìm và thay thế với IReplacingCallBack. Bạn có thể làm việc với nhiều tùy chọn trong quá trình tìm và thay thế bằng FindReplaceOptions lớp.
Tìm và Thay thế Văn bản bằng Việc Thay thế Dây Đơn giản
Bạn có thể sử dụng một trong các phương pháp Replace để tìm hoặc thay thế một chuỗi cụ thể và trả về số lần thay thế đã được thực hiện. Trong trường hợp này, bạn có thể chỉ định một chuỗi để thay thế, một chuỗi sẽ thay thế tất cả các lần xuất hiện, liệu việc thay thế có nhạy cảm với chữ hoa hay không và liệu chỉ những từ cô lập mới bị ảnh hưởng.
Mã ví dụ sau cho thấy cách tìm chuỗi " CustomerName" và thay thế nó bằng chuỗi " “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"); |
Bạn có thể nhận thấy sự khác biệt giữa tài liệu trước khi áp dụng thay thế chuỗi đơn giản:

Và sau khi áp dụng thay thế chuỗi đơn giản:

Tìm và Thay Thế Văn Bản Sử Dụng Bộ Quy Tắc Thường
Một biểu thức chính quy (regex) là một mẫu mô tả một chuỗi văn bản nhất định. Giả sử bạn muốn thay thế tất cả các lần xuất hiện của một từ với một lần xuất hiện từ duy nhất. Rồi bạn có thể áp dụng biểu thức chính quy sau để xác định mẫu từ hai từ: ([a-zA-Z]+) \1
.
Sử dụng phương thức khác Replace để tìm kiếm và thay thế các chuỗi ký tự cụ thể bằng cách đặt tham số Regex
như một mẫu biểu thức chính quy để tìm các sự phù hợp.
Mã ví dụ sau cho thấy cách thay thế chuỗi phù hợp với mẫu biểu thức chính quy bằng chuỗi thay thế được chỉ định:
// 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"); |
Bạn có thể thấy sự khác biệt giữa tài liệu trước khi áp dụng thay thế chuỗi với biểu thức chính quy:

Và sau khi áp dụng thay thế chuỗi với biểu thức chính quy là:

Tìm và Thay thế Chuỗi Sử dụng Hoặc Tạo Bằng Chữ Đặc Biệt
Bạn có thể dùng ký tự thông dụng trong chuỗi tìm kiếm hoặc chuỗi thay thế nếu một văn bản cụ thể hay cụm từ được cấu thành từ nhiều đoạn văn, phần hoặc trang. Một số ký tự siêu ký bao gồm &p cho một đoạn ngắt, &b cho một phần ngắt, &m cho một trang ngắt, và &l cho một dòng ngắt.
Mã ví dụ sau cho thấy cách thay thế văn bản với đoạn và ngắt trang:
// 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"); |
Tìm và thay thế chuỗi trong tiêu đề/xử lý của một tài liệu
Bạn có thể tìm và thay thế văn bản trong phần tiêu đề/lối chân của một tài liệu Word bằng cách sử dụng lớp HeaderFooter.
Mã ví dụ sau cho thấy cách thay thế văn bản của phần tiêu đề trong tài liệu của bạn:
// 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"); |
Bạn có thể nhận ra sự khác biệt giữa tài liệu trước khi áp dụng thay thế chuỗi tiêu đề:

Và sau khi áp dụng việc thay thế chuỗi tiêu đề:

Mẫu mã để thay thế văn bản của phần chân trang trong tài liệu của bạn rất giống với ví dụ mã đầu trước đó. Cái duy nhất bạn cần làm là thay thế hai dòng sau đây:
HeaderFooter header = headersFooters.get(HeaderFooterType.HEADER_PRIMARY);
header.getRange().replace("Aspose.Words", "Remove", options);
Với các điều sau:
Bạn có thể nhận thấy sự khác biệt giữa tài liệu trước khi áp dụng thay thế chuỗi chân đế:

Và sau khi áp dụng các thay thế chuỗi chân trang:

Làm Ngơ Đối Với Văn bản Trong Tìm và Thay Thế
Khi áp dụng chức năng tìm và thay thế, bạn có thể bỏ qua một số phân đoạn trong văn bản. Vậy, một số phần của văn bản có thể bị loại khỏi tìm kiếm và thay thế chỉ áp dụng cho các phần còn lại.
Aspose.Words cung cấp nhiều thuộc tính tìm và thay thế để bỏ qua văn bản như IgnoreDeleted, IgnoreFieldCodes, IgnoreFields, IgnoreFootnotes và IgnoreInserted.
Mã ví dụ sau cho thấy cách bỏ qua văn bản bên trong các lần sửa đổi xóa:
// 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 |
Tuỳ chỉnh hoạt động Tìm và Thay thế
Aspose.Words cung cấp nhiều các properties khác nhau để tìm và thay thế văn bản như áp dụng định dạng cụ thể với ApplyFont và ApplyParagraphFormats thuộc tính, sử dụng sự thay thế trong các mẫu thay thế với UseSubstitutions thuộc tính và những thứ khác.
Mảnh mã ví dụ sau cho thấy cách làm nổi bật một từ cụ thể trong tài liệu của bạn:
// 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 cho phép bạn dùng giao diện IReplacingCallback để tạo và gọi phương thức tùy chỉnh trong hoạt động thay thế. Bạn có thể có một số trường hợp sử dụng mà bạn cần tùy chỉnh hoạt động tìm kiếm và thay thế chẳng hạn như thay thế văn bản được chỉ định với biểu thức chính quy bằng các thẻ HTML, vì vậy cơ bản bạn sẽ áp dụng thay thế với chèn HTML.
Nếu bạn cần thay thế một chuỗi với thẻ HTML, hãy áp dụng IReplacingCallback giao diện để tùy chỉnh hoạt động tìm kiếm và thay thế để sự trùng hợp bắt đầu từ đầu của một chuỗi chạy với nút khớp của tài liệu của bạn. Hãy cung cấp một vài ví dụ về việc sử dụng IReplacingCallback.
Ví dụ mã sau cho thấy cách thay thế văn bản được chỉ định với HTML như sau:
// 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; | |
} | |
} |
Mã ví dụ sau cho thấy cách làm nổi bật số dương bằng màu xanh và số âm bằng màu đỏ:
// 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; | |
} | |
} |
Ví dụ mã sau cho thấy cách thêm số dòng vào mỗi dòng”:
// 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; | |
} | |
} |