簡體   English   中英

如何使用正則表達式匹配整個字符串

[英]How to use regular expression to match whole String

我有以下代碼:

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)
}

我希望答案是List(0) (因為它匹配'as並且index應該是0 ),但是它給了我List()

也,

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)
  }

這給了我答案List(1)但是我希望答案是List()因為我想匹配整個東西(需要完全匹配'as ),這就是為什么我在這里使用\\b

但這很好用:

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)
  }

它返回了List(12) ,這是我想要的(因為它與a's匹配並且索引應該為12 )。

我不明白為什么在我將'放在開頭'時它不起作用。 我怎樣才能做到這一點?

問題是\\b如果后面的第一個字符不是字母或其他單詞字符,則不匹配。 因此,當其后跟一個'時,它將不匹配。 請參閱: http : //www.regular-expressions.info/wordboundaries.html

編輯:

val it = ("(?:\\b|')" + "as" + "\\b").r.findAllMatchIn("'as you are a's".toLowerCase())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM