-2

I have an xml file like:

<pre>
    <book category="CHILDREN">
      <details title="Harry Potter" author="J K. Rowling">
    </book>
</pre>

How can I use substring on the string (in the xml file) and replace the author with xyzName?

Thanks in advance

Vincent
  • 1,459
  • 15
  • 37

1 Answers1

0

If you would still like to use regex for this after noting the warnings,

Use the following regex replacement:

String contents = "<pre>\n" +
                      "<book category=\"CHILDREN\">\n" +
                        "<details title=\"Harry Potter\" author=\"J K. Rowling\">\n" +
                      "</book>\n" +
                  "</pre>";
String newContents = contents.replaceFirst("(?<=author=\")[^\"]+", "xyzName");

View a regex demo!

Expression explanation:

  • (?<=author=\") Asserts that our match is after char sequence 'author="'.
  • [^\"] Matches characters that are not '"'.
    • + Once or more [greedy: match as many as possible].
Community
  • 1
  • 1
Unihedron
  • 10,902
  • 13
  • 62
  • 72