简体   繁体   English

Scala上的正则表达式-从String的开头搜索

[英]Regular expressions on Scala - Searching from the beginning of String

Currently, when I search for "th" it matches with "the" "these" and "other"...I don't want "other" because it is not at the beginning of the word. 当前,当我搜索“ th”时,它与“ the”,“ these”和“ other”相匹配...我不希望“ other”,因为它不在单词的开头。

I'm trying to use regular expressions on Scala and I am running into some problems. 我正在尝试在Scala上使用正则表达式,但遇到了一些问题。 I am having trouble implementing "\\A" which matches at the beginning of a string. 我在实现与字符串开头匹配的“ \\ A”时遇到麻烦。

I'm working on an autocomplete tool with the code seen below and currently I'm using contains...however it matches on any part of the word. 我正在使用下面显示的代码开发自动填充工具,目前我正在使用contains ...但是它与单词的任何部分都匹配。 What's the best way for it to only match from the start of the word using \\A? 仅使用\\ A从单词开头开始匹配的最佳方法是什么?

val newList = ArrayBuffer[String]()
val pattern = new Regex (\\A searchText)

def searchList (searchText:String):Unit = {
    println("Search has been called")
    println(searchText)
    for(s <- words){
        println("for test")
        if(s contains(searchText)){
            println("if test")
            newList += s
             println(newList.mkString("\n"))
        }
    }
}

使用startsWith代替contains ,从字符串的开头搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM