在特殊字符之间查找文本并替换字符串 [英] Find Text between special characters and replace string
本文介绍了在特殊字符之间查找文本并替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我有一个包含以下内容的字符串:
For instance I have a String that contains:
String s = "test string *67* **Hi**";
我想得到这个字符串:
*67*
有了星星,我就可以开始替换字符串的那部分了.我现在的代码是这样的:
With the stars, so I can start replace that part of the string. My code at the moment looks like this:
String s = "test string *67* **Hi**";
s = s.substring(s.indexOf("*") + 1);
s = s.substring(0, s.indexOf("*"));
输出:67
没有星星.
我想知道如何在某些特殊字符之间获取字符串,但不能像我想的那样将这些字符放在一起.
I would like to know how to get a string between some special character, but not with the characters together, like I want to.
输出应该如下:
//output: test string hello **hi**
推荐答案
仅替换特殊字符之间的字符串:
To replace only the string between special characters :
String regex = "(\\s\\*)([^*]+)(\\*\\s)";
String s = "test string *67* **Hi**";
System.out.println(s.replaceAll(regex,"$1hello$3"));
// output: test string *hello* **Hi**
编辑
要删除特殊字符,请使用以下正则表达式:
EDIT
To remove also the special characters use below regex:
String regex = "(\\s)(\\*[^*]+\\*)(\\s)";
这篇关于在特殊字符之间查找文本并替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文