String abc=folderDocBean.getService().replaceAll("\\s+", "_");
abc = hello world (English)
或hello world ((((English
预期输出: - hello_world_English
在上面一行中,它删除了空白处的空格和广告_
。
如果匹配的大括号()
存在,那么我想删除大括号,然后大括号需要移除所有大括号。
我尝试过使用abc.replaceAll("\\p{P}","");
删除大括号但不对我的字符串添加任何下划线
abc = abc.replaceAll("\\s+", "_");
abc = abc.replaceAll("[\\(\\)\\[\\]\\{\\}]",""); ==> it is satisfying my reqirement and how can I write the same in a single statement
答案 0 :(得分:1)
您可以使用单个表达式<?php
$post_data=@$_POST['myjson'];
$post_data=json_decode($post_data,true);
$command=$post_data['command'];
echo $command; //$command is null!
?>
编写替换,但这需要使用[()\\[\\]{}|]|\\s+
。以下是如何做到这一点:
StringBuffer
所以基本上你有一个组合的正则表达式,它拦截所有括号或多个空格然后循环遍历所有匹配,每当找到匹配时,你用public static void main(String[] args) {
String abc = "hello world ((((English)) {test}";
Pattern pat = Pattern.compile("[()\\[\\]{}|]|\\s+");
Matcher m = pat.matcher(abc);
StringBuffer bufStr = new StringBuffer();
while(m.find()) {
m.appendReplacement(bufStr, m.group().contains(" ") ? "_" : "");
}
m.appendTail(bufStr);
System.out.println(bufStr);
}
分析匹配。根据匹配是否包含空格,您可以附加m.group().contains(" ")
或空字符串。
如果您运行上面的代码,您将获得此输出:
"_"