代码之家  ›  专栏  ›  技术社区  ›  Kris B

两个值之间的正则表达式返回值?

  •  2
  • Kris B  · 技术社区  · 17 年前

    是否可以使用正则表达式返回两个字符串之间的字符串?例如,如果我有以下字符串:

    我可以用正则表达式写一个返回单词“test”的函数吗?

    编辑:对不起,我用的是C#

    4 回复  |  直到 17 年前
        1
  •  7
  •   Marc Gravell    17 年前

    既然你没有提到语言,有些C#:

        string input = "this is a :::test??? string";
        Match match = Regex.Match(input, @":::(\w*)\?\?\?");
        if (match.Success)
        {
            Console.WriteLine(match.Groups[1].Value);
        }
    

        2
  •  2
  •   Daniel C. Sobral    17 年前

    def findBetween(s: String, p1: String, p2: String) = (
      ("\\Q"+p1+"\\E(.*?)\\Q"+p2+"\\E").r 
      findFirstMatchIn s 
      map (_ group 1) 
      getOrElse ""
    )
    

    例子:

    scala> val string = "this is a :::test??? string";
    string: java.lang.String = this is a :::test??? string
    
    scala>     def findBetween(s: String, p1: String, p2: String) =
         |       ("\\Q"+p1+"\\E(.*?)\\Q"+p2+"\\E").r findFirstMatchIn s map (_ group 1) getOrElse ""
    findBetween: (s: String,p1: String,p2: String)String
    
    scala> findBetween(string, ":::", "???")
    res1: String = test
    
        3
  •  0
  •   Jim Lewis    17 年前

    是的,在正则表达式中,您可以提供您想要匹配的前后“上下文”,然后使用捕获组返回您感兴趣的项目。

        4
  •  0
  •   Gabriel Hurley    17 年前

    如果:::和???您的delimeters是否可以使用正则表达式,如:

    :::(.*)\?\?\?
    

    中间的部分将从比赛中作为被捕获的组返回。