Find string

Below is my code to find all words in textfield search.text and highlight them.
It does highlight all the words I search, but also many other words. I don’t know how I can make it work.

dim rg as regex
dim m as regexMatch
dim s,t as string
dim i,k,n as integer

mainwindow.editarea.selStart=0
mainwindow.editarea.selLength=65536
mainwindow.editarea.selTextColor=rgb(0,0,0)

s=mainwindow.EditArea.text
rg=new RegEx
rg.SearchPattern = search.text

m=rg.search(s)
while m<>nil
t=m.subExpressionString(0)
k=m.subExpressionStartB(0)
n=LenB(t)
mainwindow.editarea.selStart=k
mainwindow.editarea.selLength=n
mainwindow.editarea.selTextColor=rgb(255,0,0)
m=rg.search(s,k+n)
wend
mainwindow.editarea.selLength=-1
self.close

Have a look at this old project:

https://dl.dropboxusercontent.com/u/992591/REALbasic/Forum/bitbatbut.rb.zip

Think I got it from Kem.

It’s exactly the same code. Your project works well, but when I use it in my project it doesn’t

Couple of things.

The second rg.Search does not need the text or position. Just call it as rg.Search() and it will pickup where it left off.

If you text contains any characters whose code point > 127, this code won’t work right no matter what. You have to convert LenB to Len and the starting position from the byte position to the character position.

Can you post a screen shot of what you get when you run this code?

Markus Winter Very Good, Tanks for sharing !

Kem,

Sometimes the search word is highlighted, sometimes a word in the line of the search word is highlighted.

Please post a screen shot. I have a feeling you’re running into the multi-byte character problem I alluded to.

The word to search for is “ls”

Try this:

  m=rg.search(s)
  while m<>nil
    t=m.subExpressionString(0)
    k=m.subExpressionStartB(0)
    mainwindow.editarea.selStart=s.LeftB( k ).Len
    mainwindow.editarea.selLength=t.Len
    mainwindow.editarea.selTextColor=rgb(255,0,0)
    m=rg.search()
  wend

I tried some words for searching and with your code it works. Thanks

Remember, RegEx returns its position in bytes, but a TextArea expects it by characters (LenB vs. Len).