How to remove part of a string from another string by keeping some of it conditionally in Java?

I have string and I modify this string using the code below:

The input is:

-f S:\some\keyword\path\to\a\file.c
-d C:some\other\path\to\keyword\another\file.cpp

Open in new window

The code that I use is:

content = content.replaceAll("(?m)^.*?(?=keyword)", "")

Open in new window

The output is this:


Open in new window

Now, I would like to change this regexp in such a way that the output will be like this for the same input:

Expected output:

-d keyword\another\file.cpp

Open in new window

As you can see, the difference between the previous output and this one is the -d flag in the front. The idea is to keep the -d flag if there is any and do the rest same.

The input data is in one big string. I would prefer to do it in one regexp instead of looping through the lines.

How can I do?

Who is Participating?
Terry WoodsConnect With a Mentor IT GuruCommented:
Try this:
content = content.replaceAll("(?m)^(-d\\s)?.*?(?=keyword)", "$1")

Open in new window

TolgarAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.