skip to Main Content

I have a huge amount of files with elements containing an id. I would like to copy the value of the id and create a new attribute with the value of the id:

<element id="some_unique.value">
    ...      
</element>

What I’m trying to achieve:

<element id="some_unique.value" new_attribute="some_unique.value">
    ...      
</element>

How can I do this using a regular expression? I’m looking for a regex that I can use in my IDE (Visual Studio Code) to quickly change multiple files.

2

Answers


  1. Capture the part you want to reuse as a group and use a back reference to construct the result.

    Search:

    <element id="([^"]+)"
    

    Replace:

    <element id="$1" new_attribute="$1">
    
    Login or Signup to reply.
  2. As in my comment try matching:

    id="([^"]+)"
    

    and replace with

    $0 new_attribute="$1"
    

    See: regex101


    Explanation

    Match:

    • id="...": match literal id and text in quotation
      • ([^"]+): that is not quotation marks. save this to group 1

    Replace:

    • $0: keep original data
    • new_attribute=": add literal ‘ new_attribute=’
    • ": open quotation
    • $1: insert group 1 (quoted id text) and
    • ": close quotation
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search