Search code examples
regexpcregambas

How can I replace two exact words separated by a whitespace using PCRE?


I've been trying to code a simple translator using Gambas and I'm stuck on replacing two exact words separated by a whitespace using PCRE, which is a built-in component on Gambas.

The languages are Turkish and Uzbek. The exact phrase I want to replace is "görmek istiyorum", which literally means "I want to see".

  If ComboBox1.Text = "Turkish" And ComboBox2.Text = "Azerbaijani" Then 
    TextArea2.Text = TextArea1.Text
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bbana\\b", "mənə")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bben\\b", "mən")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bbenden\\b", "məndən")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bbeni\\b", "məni")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bbenim\\b", "mənim")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bistiyor\\b", "istəyir")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bo\\b", "o")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bseviyor\\b", "sevir")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bsevmek\\b", "sevmək")
   Else If ComboBox1.Text = "Turkish" And ComboBox2.Text = "Uzbek" Then
    TextArea2.Text = TextArea1.Text
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bben\\b", "men")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bbenim\\b", "mening")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bgörmek\\b", "ko‘rmoq")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bgörmek\\b\\h\\bistiyorum\\b", "ko‘rmoqchiman")
  Endif

I expected it to replace the phrase from "görmek istiyorum" to "ko‘rmoqchiman", but the output was "ko‘rmoq istiyorum", which is mixed.


Solution

  • Okay, so the problem is with the following two lines:

    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bgörmek\\b", "ko‘rmoq")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bgörmek\\b\\h\\bistiyorum\\b", "ko‘rmoqchiman")
    

    The first line replaces "görmek" with "ko‘rmoq" so the phrase "görmek istiyorum" becomes "ko‘rmoq istiyorum". Now when the second line checks this text for the regex "görmek istiyorum", it returns false.

    To correct it, you should check the largest regex match first. So just switching the lines should work:

    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bgörmek\\b\\h\\bistiyorum\\b", "ko‘rmoqchiman")
    TextArea2.Text = RegExp.Replace(TextArea2.Text, "\\bgörmek\\b", "ko‘rmoq")