简体   繁体   中英

Regex to replace a substring in java

I have a list containing strings like below

/b/Xfassds12312/5324234/img1.jpg
/b/asda33CSds/765345/img1.jpg
/b/iop98plkKLJ/2421466/img1.jpg
/b/nzcbWWSJk/3424535/img1.jpg

I need to replace the /b/ to /img/ in every string of that list.

I tried the below pattern.. looks like it appending instead of replacing.. not sure what I'm missing

replaceFirst("(/[^/]*)", "$1" + "img");

If the other strings would not breaks, just use yourString.replace("/b/", "/img/");

Use

String output = yourString.replaceFirst("^/[^/]+", "/img");

See proof .

VISUAL:

在此处输入图像描述

EXPLANATION:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  /                        '/'
--------------------------------------------------------------------------------
  [^/]+                    any character except: '/' (1 or more times
                           (matching the most amount possible))

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