Macro: Find and Replace maintaining case of the word being replaced

I have a macro that finds words in one array and replaces them with corresponding ones in another. Essentially it is:

BritWords() = Array("fibre", "foetal")
	USWords() = 	Array("fiber", "fetal")
	Doc = ThisComponent
	Replace = Doc.createReplaceDescriptor
	 
	For I = LBound(BritWords()) To UBound(BritWords())
	  Replace.SearchString = BritWords(I)
	  Replace.ReplaceString = USWords(I)
	  Doc.replaceAll(Replace)
	Next I

It works great, but with the problem that the case of replacement word is imposed on the original word. So in the above case, if “Fibre” is at the beginning of a sentence, and thus is capitalized, it will be replaced with “fiber”, which is a usage error.

So I’m looking for a way to respect the case of the word being replaced. Would it be to capture the capitalization state and then impose it immediately after the replacement? Or is there a parameter that could be set for .doc.replaceAll(Replace) (perhaps involving Regex if no other way?) to carry the case through? Thanks.

Unless you would use some smart library, you will have to do it manually:

  1. Find a case-insensitive match.
  2. Build a vector of “upper/lower case” flags for each character (or, if only the first character matters, then it is a sole “start with upper/lower case” flag).
  3. Apply it to the replacement (for the simple “first character” case, it’s trivial; for the “each character” case, you would have to decide what to do with character count mismatch - or even with a case of different count of words between the match and replacement).
  4. Do the replacement with the prepared result from #3.

Thanks. I think you’re saying what I was trying to get at. I understand the concept, actually coding it is another matter.

1 Like

By the way, even the “trivial” cases that I mention above, aren’t completely trivial: you also need to consider cases where the found matches start in the middle of a word; what to do with the replacements with mixed or upper case, etc., etc.

Yes, true. I did notice that the doc.replaceAll(Replace) catches strings, not just whole words. But even if it’s not perfect, doing it this way clears up a lot of problems.