Ozuf Ozuf - 8 months ago 19
Java Question

Replace some part of a sentence with empty space

I am trying to replace this string

String sampl = "Mab by Gap David . Leave my Food"

with this code:

String authorf = sampl.replace(".","").replaceAll("Leave.","");

so that at the end I will have only
Mab by Gap David

But currently I am getting
Mab by Gap David my Food

Please how do I get only
Mab by Gap David


If you want just the first sentence, that means deleting anything after the sentence terminator.

From your example, it seems you want the sentence terminator itself to be removed too. Removing any spaces before the terminator seems logical as well.

A sentence terminator can be defined as a period (.), a question mark (?), or an exclamation point (!). You can of course decide for yourself what sentence terminators you want.

So. Find a sentence terminator: [.?!]
Also select any spaces before: \s*[.?!]
Also select anything after: \s*[.?!].*

So your code would be:

String authorf = sampl.replaceAll("\\s*[.?!].*","");

See regex101.com for example.