I would not recommend using a regex for this particular application. Yes, it is possible however norm's suggestion of using indexOf() and lastIndexOf() is more efficient and likely more maintainable/readable (as suggested by other users lack of experience with regex).
To write to a file:
The simplest method is to use a
PrintStream. This is the same class that System.out and System.err use so the interface will be similar.
Simply pass the file name string. Note that this constructor will create a blank file to write to. If the file already exists, it's first deleted.