How to search for ${foo} and replace by

2019-07-22 11:12发布

Is there a regex to replace the outer part of a string while keeping the inner part?

before:

${person.dog.name}

after:

<c:out value="${person.dog.name}"/>

I need to use it in Eclipse editor, and the inner part changes.


This can be useful too:

Search: \$\{(.*?)\}

Replace:\$\{fn:escapeXml\($1\)\}

${person.dog.name}

become

${fn:escapeXml(person.dog.name)}

2条回答
何必那么认真
2楼-- · 2019-07-22 11:52

Find expression with:

(\$\{[^\}]+\})

and replace expression will be:

<c:out value="$1"/>

To find ${person.dog.name} with <c:out value="${person.dog.name}"/> in Eclipse editor!

Edit:

Be careful while using it, because <c:if test="${foo}"> will end up like <c:if test="<c:out value="${foo}" />">

查看更多
Ridiculous、
3楼-- · 2019-07-22 12:12

Just capture the entire string with ^(.*)$ and then use in the replace function use a back reference like <c:out value="$1"/> where the $1 is the backreference

string.replaceAll("^(.*)$", "<c:out value=\"$1\"/>")

In eclipse see link. You'd put ^(.*)$ into find, <c:out value="$1"/> into replace. select regular expressions, click find and replace.

If you're looking to capture all the ${foo} with <c:out value="${foo}"/>? in some larger text then you'll have to use the regex ([$]{foo}) to find all the desired text then use <c:out value=\"$1\"/> in the replace field.

查看更多
登录 后发表回答