Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 两个值之间的正则表达式返回值?_C#_Regex_String - Fatal编程技术网

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

C# 两个值之间的正则表达式返回值?,c#,regex,string,C#,Regex,String,是否可以使用正则表达式返回两个字符串之间的字符串?例如,如果我有以下字符串: string=“这是一个:::测试???字符串” 我可以用正则表达式写一个返回单词“test”的函数吗 编辑:抱歉,我使用的是C#是的,在正则表达式中,您可以提供您想要匹配的前后“上下文”,然后使用捕获组返回您感兴趣的项目 既然你没有提到语言,有些C#: :::和??????您的delimeters是否可以使用正则表达式,如: :::(.*)\?\?\? 中间的部分将作为匹配的捕获组返回。 < P>因为你忘了指示语言

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

string=“这是一个:::测试???字符串”

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


编辑:抱歉,我使用的是C#

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

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


<确切的正则表达式将取决于你认为什么匹配……一个词?什么?等等)

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

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

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

< P>因为你忘了指示语言,我将在Scala中回答:

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

对如果你想要一个例子,最好陈述一个实现……好吧,对于C#信息来说太晚了。顺便说一下,根据我的参考资料,\Q和\E不适用于.Net语言,因此转换它可能不起作用。\Q和\E在c#中不起作用,但您可以使用Regex.Escape函数:Regex.Escape(p1)+“(.?”+Regex.Escape(p2)
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