Home > OS >  Optional grouping with Regex in Eclipse
Optional grouping with Regex in Eclipse

Time:10-04

I have a file with many different file path locations. Some of them have multiple directory depth and some don't. What I need to do is prepend a directory /WEB_ROOT/ to all file path locations in the file.

For example

index.jsp -> /WEB_ROOT/index.jsp

/instructor/assigned_appts.jsp -> /WEB_ROOT/instructor/assigned_appts.jsp

I have tried this one ([\/_]?[A-Za-z]*).jsp to try and capture the optional _ and / values but this doesn't match properly.

/instructor/assigned_appts.jsp only matches _appts.jsp

I have tried this as well ([\/_]?[A-Za-z])*.jsp which properly matches all expected file paths but when I replace I only get the last letter instead of the full group

So a replace with /WEB_ROOT/$1.jsp gives the following

index.jsp -> /WEB_ROOT/x.jsp

/instructor/assigned_appts.jsp -> /WEB_ROOT/s.jsp

Help please!

CodePudding user response:

You can match the whole line, and as [\/_]? is optional, make sure that you match at least a single char A-Za-z before the .jsp

If you want to replace with group 1 like /WEB_ROOT/$1 you can also capture the .jsp

(.*[A-Za-z]\.jsp)

Note sure if supported in eclipse, but you might also just get the whole match and use $0 instead of group 1

.*[A-Za-z]\.jsp

If .jsp is at the end of the string, you can append an anchor .*[A-Za-z]\.jsp$

  • Related