#1786 findAll in str

Xan Fri 24 Feb 2012

Hi,

I see that in API of String there is no findAll(substring str) which returns all the indexs of str in a string.

Is it possible to include in future release? I think this is useful.

If not, how can I implement it?

Thanks in advance, Xan.

brian Fri 24 Feb 2012

Doesn't seem like something I've ever really encountered. What is your use case?

To implement yourself you can do this:

str := "abc abc abc"
indices := Int[,]
Int? i := -1
while (true)
{
  i = str.index("abc", i+1)
  if (i == null) break
  indices.add(i)
}
echo(indices)

Xan Fri 24 Feb 2012

Thank you very much Brian. My case is to search all links in one web page, that is search string "<a href=" in web page string (very large string).

Do you recommend this code or use Buffer?

Thanks a lot, a lot, Xan.

KevinKelley Sat 25 Feb 2012

Likely Regex and RegexMatcher can work for you...

indices := Int[,]
str := "a very long string to look for words in"

regex := Regex("[a-z]+")
matcher := regex.matcher(str)
while (matcher.find) {
  indices.add(matcher.start)
}
echo(indices)

gives

[0, 2, 7, 12, 19, 22, 27, 31, 37]

brian Sat 25 Feb 2012

Do you recommend this code or use Buffer?

Well an in-memory string is probably simplest and fine.

If I was doing this for production software, I'd probably use a real HTML parsing library or write one myself (knowing me I'd write one myself because I love that sort of thing :-)

Xan Mon 27 Feb 2012

Thank you Kevin. Definitely RegexMatcher is the tool I need ;-)

Thanks also Brian for suggestion about performance.

Login or Signup to reply.