当前位置:主页 > >

正则表达式去除中括号(符号)及里面包含的内容

时间:2021-01-22 12:26:57 | 栏目: | 点击:

例子:颜色:粉色[10] 尺码:S[5]

去掉[ ]及内容:

preg_replace("/\[.*\]/", '', $str)1

处理后效果:颜色:粉色 尺码:S

小技巧:可把[ ]改为其他符号应用在需要的地方

ps:下面看下利用正则表达式提取括号内内容

比如现在要提取  中华人们共和国,简称(中国) 这句话中括号里的“中国”

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test
{
  public static void main(String[] args)
  {
    String str ="中华人民共和国,简称(中国)。";
    Matcher mat = Pattern.compile("(?<=\\()(\\S+)(?=\\))").matcher(str);//此处是中文输入的()
    while(mat.find()){
      System.out.println(mat.group());
    }
  }
}

最后附一下用到的零宽断言:


总结

您可能感兴趣的文章:

相关文章