简体   繁体   中英

How to replace a given substring with “” from a given string?

I went through a couple of examples to replace a given sub-string from a given string with "" but could not achieve the result. The String is too long to post and it contains a sub-string which is as follows:-

/image/journal/article?img_id=24810&t=1475128689597

I want to replace this sub-string with "".Here the value of img_id and t can vary, so I would have to use regular expression. I tried with the following code:-

String regex="^/image/journal/article?img_id=([0-9])*&t=([0-9])*$";
content=content.replace(regex,"");

Here content is the original given string. But this code is actually not replacing anything from the content . So please help..any help would be appreciated .thanx in advance.

Use replaceAll works in nice way with regex

content=content.replaceAll("[0-9]*","");

Code

String content="/image/journal/article?img_id=24810&t=1475128689597";
content=content.replaceAll("[0-9]*","");
System.out.println(content);

Output :

/image/journal/article?img_id=&t=

Update : simple, might be little less cozy but easy one

    String content="sas/image/journal/article?img_id=24810&t=1475128689597";
    content=content.replaceAll("\\/image.*","");
    System.out.println(content);

Output:

sas

If there is something more after t=1475128689597/?tag=343sdds and you want to retain ?tag=343sdds then use below

    String content="sas/image/journal/article?img_id=24810&t=1475128689597/?tag=343sdds";
    content=content.replaceAll("(\\/image.*[0-9]+[\\/])","");
    System.out.println(content);
    }

Output:

sas?tag=343sdds

If you're trying to replace the substring of the URL with two quotations like so:

/image/journal/article?img_id=""&t=""

Then you need to add escaped quotes \\"\\" inside your content assignment, edit your regex to only look for the numbers, and change it to replaceAll:

content=content.replaceAll(regex,"\"\"");

You can use Java regex Utility to replace your String with "" or (any desired String literal), based on given pattern (regex) as following:

String content = "ALPHA_/image/journal/article?img_id=24810&t=1475128689597_BRAVO";
String regex = "\\/image\\/journal\\/article\\?img_id=\\d+&t=\\d+";
Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
    String replacement = matcher.replaceAll("PK");
    System.out.println(replacement); // Will print ALPHA_PK_BRAVO
}

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