Search and reassign WORD ONLY in VB

The word processor program has a search and replace function. However, partial words (character combinations found in words) are also replaced. To fix this, I plan to remove the extra spaces and use the split function to change the string into an array of words, using "" as a separator.

However, as soon as I look through the array, replace the corresponding words and return the array to a string separated by spaces, the original user formatting will be lost. For example, if the source string was "This sentence". , and the user wanted "a" to be replaced by "the", the output would be "This sentence", without additional spaces.

So my question is, is there a way to search and replace whole words only while maintaining the user’s formatting (extra spaces) in Visual Basic. Thanks.

+4
source share
3 answers

If you use the Split function without removing extra spaces, first your array will have empty elements, so you will not lose extra spaces and you can restore the document with the original formatting to the beat.

+1
source

How to use regex?

In a regular expression, the code \b is the word boundary, therefore, for example, the regular expression \ba\b will match only when a is a whole word.

So, for example, your code would look like this:

 Dim strPattern As String: strPattern = "\ba\b" Dim regex As New RegExp regex.Global = True regex.Pattern = strPattern result = regex.Replace("This is a sentence.", "the") 
+4
source

Why is your formatting lost? If you separate the text by space, just attach the space after each element when creating it from the array. But you also have to consider words that end not with a space, but with punctuation.

in "This is a simple sentence, huh?", "eh" will be stored as "ah?" because u is split by a space. Thus, you will need to program a complex formula equivalent to punctuation, or just use a regular expression. Get ready - regular expression ... complicated.

+1
source

Source: https://habr.com/ru/post/1441392/


All Articles