简体   繁体   中英

Using regular expressions to rename a string

In java, I want to rename a String so it always ends with ".mp4"

Suppose we have an encoded link, looking as follows:

String link = www.somehost.com/linkthatIneed.mp4?e=13974etc...

So, how do I rename the link String so it always ends with ".mp4"?

link = www.somehost.com/linkthatIneed.mp4  <--- that's what I need the final String to be.

Just get the string until the .mp4 part using the following regex :

^(.*\\.mp4)

and the first captured group is what you want.

Demo: http://regex101.com/r/zQ6tO5

Another way to do this would be to split the string with ".mp4" as a split char and then add it again :)

Something like :

String splitChar = ".mp4";
String link = "www.somehost.com/linkthatIneed.mp4?e=13974etcrezkhjk"
String finalStr = link.split(splitChar)[0] + splitChar;

easy to do ^^

PS: I prefer to pass by regex but it ask for more knowledge about regex ^^

Well you can also do this:

Match the string with the below regex

\?.*

and replace it with empty string.

Demo: http://regex101.com/r/iV1cZ8

Try below code,

  private String trimStringAfterOccurance(String link, String occuranceString) {

    Integer  occuranceIndex =  link.indexOf(occuranceString);

    String trimmedString = (String) link.subSequence(0, occuranceIndex + occuranceString.length() );    

    System.out.println(trimmedString);

    return trimmedString;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM