Check if a string contains a substring. Additionally, get index and number of match (Raku)

天大地大妈咪最大 提交于 2020-04-12 20:22:55

问题


FAQ: In Raku, how to check if a String contains a substring ? Where and how many times ? I would like 3 functions such as:

xxx-bool("az and az and az again", "az");  # True 
xxx-num("az and az and az again", "az");   # 3
xxx-list("az and az and az again", "az");  # (0 7 14) 

PS: Routines index and rindex are pretty cool but only get one match.

Related Links:

  • Answer with Regex
  • Answer on List (Array)
  • Contiguous Sequences on List
  • Answer on Hash (Dictionary)

回答1:


  1. To check if it contains, use .contains to get a Bool which is a cool method.
  2. To get indices (alias indexes: both are plural of index) use .indices
  3. To get number, count the indices.
"az and az and az again".contains("az");        # True
"az and az and az again".indices("az").elems;   # 3
"az and az and az again".indices("az");         # (0 7 14)

PS: Routine indices is described just after index and rindex. So read the good doc, and read it well ;-)

  • Links:

    • contains in regex
    • Same question in Python, Perl


来源:https://stackoverflow.com/questions/60853431/check-if-a-string-contains-a-substring-additionally-get-index-and-number-of-ma

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!