简体   繁体   中英

Replace a string using Regular Expression

I am trying to replace a media query in CSS text using c#

I only have the declaration

 @media  screen and (min-width:1500px)

I also have the new media

@media  screen and (min-width:1500px)
{  
 .g{
     border:1px solid red;
   }
}

My goal is to replace the old media with the new one using regexr

I manged to make this task here

http://regexr.com/3a58a

using this expression

@media\s*screen\sand[\s*]\(min-width:1500px\)([\s,\n,\r]*\{[\s,\n,\r]*.*[\s,\n,\r]*[\s,\n,\r]*.*[\s,\n,\r]*\}*\s*\})

but in c# it seem to mark the media and all the roles beneath it,instead of marking only the media.

this is the c# that handle the case

  NewCss= Regex.Replace(cssContent, Media_declaration.Replace(" ", "[\\s,\\n,\\r]*").Replace("(", "\\(").Replace(")", "\\)") + @"([\s,\n,\r]*\{[\s,\n,\r]*.*[\s,\n,\r]*[\s,\n,\r]*.*[\s,\n,\r]*\}*\s*\})", new MatchEvaluator(mediaNeVal), RegexOptions.Singleline);

where

Media_declaration=@media screen and (min-width:1500px)

is it possible to mark only the media query using the Media_declaration, so I can replace the Specific text?

The expression you used matches all text up to the last brace because it uses (in two places) the greedy .* . Use the non-greedy .*? instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM