是否有可能使用正則表達式返回2個字符串之間的字符串?例如,如果我有這個字符串:正則表達式返回兩個值之間的值?
string =「this is a ::: test ??? string」;
我可以寫一個函數來使用正則表達式返回單詞「測試」嗎?
編輯:對不起,我使用C#
是否有可能使用正則表達式返回2個字符串之間的字符串?例如,如果我有這個字符串:正則表達式返回兩個值之間的值?
string =「this is a ::: test ??? string」;
我可以寫一個函數來使用正則表達式返回單詞「測試」嗎?
編輯:對不起,我使用C#
既然你不提語言,一些C#:??
string input = "this is a :::test??? string";
Match match = Regex.Match(input, @":::(\w*)\?\?\?");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
(確切的正則表達式彭定康將取決於你認爲什麼是比賽......一個字等什麼..)
是的,在你的正則表達式,你可以之前提供/「上下文」周邊要匹配什麼後,然後用捕獲組返回的項目你」 。重新興趣
if :::和???是你的delimeters你可以使用正則表達式,如:
:::(.*)\?\?\?
而中間的部分將作爲匹配的捕獲組返回。
既然你忘了表示語言,我會在斯卡拉回答:
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語言,因此將其轉換可能不起作用。 – 2009-08-17 21:37:45
\ Q和\ E在c#中不起作用,但您可以使用Regex.Escape函數:Regex.Escape(p1)+「(。*?)」+ Regex.Escape(p2) – Jirka 2012-10-19 13:22:26
這langage好嗎? :-) – 2009-08-17 21:26:34
是的。如果你想要一個例子,你會很好地陳述一個實現...... – 2009-08-17 21:26:59