We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Replace multiple line text with a single line text

I am trying to replace multiline text like address with a single line text. But it’s not working. Please help.
Example text:
Address line 1,
Address line 2, City Pincode

@gkumar16 If lines are separated by a paragraph break, you should use special metacharacter &p in your search pattern:

Document doc = new Document("C:\\Temp\\in.docx");
doc.getRange().replace("Address line 1,&pAddress line 2, City Pincode", "one line");

in.docx (12.4 KB)
out.docx (9.8 KB)

If the lines are separated by soft line break (Shift+Enter) then you should &l metacharacter.
Please see our documentation for more information:

Thanks @alexey.noskov. It worked.

I have one another use case where I don’t know where the line break is. Is it possible to search and replace in that case?

Example Search text: Address line 1,Address line 2, City Pincode

@gkumar16 You can use regular expression. For example see the following code:

Document doc = new Document("C:\\Temp\\in.docx");
Pattern regex = Pattern.compile("Address line 1,((&p)|(\\s+)|(\u000b))Address line 2, City Pincode");
doc.getRange().replace(regex, "one line");

in.docx (12.5 KB)
out.docx (10.0 KB)

In the regular expression the following special symbols are used:

  • &p - Paragraph break;
  • \\s+ - one or more whitespaces;
  • \u000b - soft line break.

The address will not be properly line break like above.
For example,
Apt. 887 7977 Guillermo Brook, New
Yaekoport, ME 93650

or no comma at the end of line
Apt. 887 7977 Guillermo Brook
New Yaekoport, ME 93650

@gkumar16 You can adjust regular expression to match the address format in your documents. Please see the following link for a fast start with regular expressions:
There are a lot of sites where you can test your regular expressions, like this: