Reputation: 2229
I have the following code:
def main(args: Array[String]) {
val it = ("\\b" + "'as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase());
val lst = it.map(_.start).toList
print(lst)
}
I expected the answer would be List(0)
(because it matched 'as
and index should be 0
), but it gave me List()
Also,
def main(args: Array[String]) {
val it = ("\\b" + "as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase());
val lst = it.map(_.start).toList
print(lst)
}
This gave me the answer List(1)
but I expected the answer to be List()
because I want to match the whole thing (need exactly match 'as
), that is why I use \b
here
But this worked well:
def main(args: Array[String]) {
val it = ("\\b" + "a's" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase());
val lst = it.map(_.start).toList
print(lst)
}
it returned List(12)
which is what I want (because it matched a's
and index should be 12
).
I did not understand why it did not work when I put '
at the front of word. How can I do this?
Upvotes: 1
Views: 95
Reputation: 9100
The problem is \b
does not match if the first character after that is not a letter or other word character. So it will not match when it is followed by a '
. See: http://www.regular-expressions.info/wordboundaries.html
Edit:
val it = ("(?:\\b|')" + "as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase())
Upvotes: 1