开发者

regular expressions to add a slash to the end of a generic string of words

I'm in notepad++ and I need to add a / right before the closing > in the following line:

<meta name="description" content="*****">

the ***** above is a bunch of text that I need left in place, and it changes from page to page, thus my need for some find / replace method that is superior to what I would normally be capable开发者_如何学JAVA of. I assume regex would be the right way to go.


This seems to do the trick for me (in NP++):

Find: (<meta name="description" [^>]+)>

Replace with: \1/>

Has some caveats, but it'll work for a simple search/replace, which it sounds like you're doing. Was I right in assuming that you're trying to only do this on <meta> tags with attributes of name="description"?

Edit - Tested it with the Replace All button and went from this:

<meta name="description" content="ljfkdl">
<meta name="description" content="039814">
<meta name="description" content="lkjai983j">
<meta name="description" content="whak.dlai3#">
<meta name="description" content="ljfdal&&3lk">
<meta name="description" content="a b c ake87">
<meta name="description" content="">
<meta name="description" content="memememe">
<meta name="description" content="alkd3988aj38#!">

To this:

<meta name="description" content="ljfkdl"/>
<meta name="description" content="039814"/>
<meta name="description" content="lkjai983j"/>
<meta name="description" content="whak.dlai3#"/>
<meta name="description" content="ljfdal&&3lk"/>
<meta name="description" content="a b c ake87"/>
<meta name="description" content=""/>
<meta name="description" content="memememe"/>
<meta name="description" content="alkd3988aj38#!"/>


Based on these assumptions:

  • Tags are all almost well-formed except for the missing / i.e. no raw > characters within attributes, etc
  • The value of the name attribute is disregarded since all <meta /> tags should self-close anyway

Find:

(<meta[^>]*)[^/]>

Replace with:

\1 />


Though HTML and regular expressions don't usually mix well, this seems like a simple enough of a case. (I'm assuming that you're looking for all meta tags, and don't care about what else is inside. Being more specific can be helpful, though :D)

<(meta[^>]+)>

Will find content between < and > and return that inner content as a subgroup.

Depending on the Notepad++ notation, you should replace with something like this:

<\1/>

(Or possibly $1 instead of \1, or something else entirely. Again, dunno what Notepad++ wants.)

This regular expression doesn't catch cases in which > is part of an attribute, like <fake-math-tag expression="4 > 2"> but is probably good enough for your situation. (This is where the "don't mix well" bit kicks in.)


Searching text: <(meta.*)>
Replace to: <\1/>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜