簡體   English   中英

正則表達式以匹配模式

[英]Regular Expression to match the pattern

我正在尋找正則表達式搜索模式以查找$<>$內的數據。

string pattern = "\b\$<[^>]*>\$"; 

不管用。

謝謝,

您可以使用脾氣暴躁的令牌

\$<(?:(?!\$<|>\$)[\s\S])*>\$

觀看演示

這樣,您將僅匹配最接近的邊界。

您的正則表達式不匹配,因為您不允許在標記之間使用> ,並且您正在使用\\b ,而您最可能沒有單詞邊界。

如果不想在輸出中獲取定界符,請使用捕獲組:

\$<((?:(?!\$<|>\$)[\s\S])*)>\$
   ^                      ^

結果將在第1組中

在C#中,您應該考慮借助逐字字符串文字符號(帶有@"" )聲明所有正則表達式模式(如果可能),因為您不必擔心加倍反斜杠:

var rx = new Regex(@"\$<(?:(?!\$<|>\$)[\s\S])*>\$");

或者,由於存在單行標記(這是更好的選擇):

var rx = new Regex(@"\$<((?:(?!\$<|>\$).)*)>\$", RegexOptions.Singleline | RegexOptions.CultureInvariant);
var res = rx.Match(text).Select(p => p.Groups[1].Value).ToList();

此模式將完成工作:

(?<=\$<).*(?=>\$)

演示: https//regex101.com/r/oY6mO2/1

要在php中找到此模式,您可以使用此REGEX代碼來查找任何模式,

/$<(.*?)>$/s

例如:

        $arrayWhichStoreKeyValueArrayOfYourPattern= array();
        preg_match_all('/$<(.*?)>$/s', 
        $yourcontentinwhichyoufind,         
        $arrayWhichStoreKeyValueArrayOfYourPattern);
        for($i=0;$i<count($arrayWhichStoreKeyValueArrayOfYourPattern[0]);$i++)
        {
            $content=
                     str_replace(
                      $arrayWhichStoreKeyValueArrayOfYourPattern[0][$i], 
                      constant($arrayWhichStoreKeyValueArrayOfYourPattern[1][$i]), 
                      $yourcontentinwhichyoufind);
        }

使用此示例,您將在此變量$ yourcontentin中找到使用相同名稱常量內容替換的值

例如,您具有類似這樣的字符串,它也具有相同的命名常量。

**global.php**
//in this file my constant declared.

define("MYNAME","Hiren Raiyani");
define("CONSTANT_VAL","contant value");

**demo.php**
$content="Hello this is $<MYNAME>$ and this is simple demo to replace $<CONSTANT_VAL>$";
$myarr= array();
        preg_match_all('/$<(.*?)>$/s', $content,      $myarray);
        for($i=0;$i<count($myarray[0]);$i++)
        {
            $content=str_replace(
                      $myarray[0][$i], 
                      constant($myarray[1][$i]), 
                      $content);
        }

我想我知道就這些。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM