2009-08-17 66 views
2

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

string =“this is a ::: test ??? string”;

我可以写一个函数来使用正则表达式返回单词“测试”吗?

编辑:对不起,我使用C#

+1

这langage好吗? :-) – 2009-08-17 21:26:34

+1

是的。如果你想要一个例子,你会很好地陈述一个实现...... – 2009-08-17 21:26:59

回答

7

既然你不提语言,一些C#:??

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

(确切的正则表达式彭定康将取决于你认为什么是比赛......一个字等什么..)

0

是的,在你的正则表达式,你可以之前提供/“上下文”周边要匹配什么后,然后用捕获组返回的项目你” 。重新兴趣

0

if :::和???是你的delimeters你可以使用正则表达式,如:

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

而中间的部分将作为匹配的捕获组返回。

2

既然你忘了表示语言,我会在斯卡拉回答:

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 
+0

对于C#信息来说,已经太晚了。顺便说一下,根据我的参考,\ Q和\ E将不能用于.Net语言,因此将其转换可能不起作用。 – 2009-08-17 21:37:45

+0

\ Q和\ E在c#中不起作用,但您可以使用Regex.Escape函数:Regex.Escape(p1)+“(。*?)”+ Regex.Escape(p2) – Jirka 2012-10-19 13:22:26

相关问题