Java 用已知的开始和结束替换字符串的一部分

Java 用已知的开始和结束替换字符串的一部分,java,android,Java,Android,我从服务器上得到一些字符串,其中包含已知和未知的部分。例如: <simp>example1</simp><op>example2</op><val>example2</val> example1example2example2 我不希望解析XML或任何解析的使用。我想做的是替换 <op>example2</op> 示例2 使用空字符串(“”),哪个字符串看起来像: <simp>ex

我从服务器上得到一些字符串,其中包含已知和未知的部分。例如:

<simp>example1</simp><op>example2</op><val>example2</val>
example1example2example2
我不希望解析XML或任何解析的使用。我想做的是替换

<op>example2</op>
示例2
使用空字符串(“”),哪个字符串看起来像:

<simp>example1</simp><val>example2</val>
example1example2
我知道它以op(in)开始,以/op(in)结束,但内容(示例2)可能会有所不同


你能告诉我如何做到这一点吗?

你可以使用正则表达式。差不多

<op>[A-Za-z0-9]*<\/op>
[A-Za-z0-9]*
应该匹配。但您可以对其进行调整,使其更好地满足您的需求。例如,如果您知道只能显示某些字符,则可以对其进行更改。 之后,您可以使用String#replaceAll方法删除所有匹配的空字符串

请查看此处以测试正则表达式: 在这里检查以regex和replacement作为参数的replaceAll方法:

您可以尝试

str.replace(str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5),"");
我试过样品

String str="<simp>example1</simp><op>example2</op><val>example2</val><simp>example1</simp><op>example2</op><val>example2</val><simp>example1</simp><op>example2</op><val>example2</val>";
Log.d("testit", str.replaceAll(str.substring(str.indexOf("<op>"), str.indexOf("</op>") + 5), ""));
String str=“example1example2example2example2example2example2example2example2example2example2example2”;
Log.d(“testit”,str.replaceAll(str.substring(str.indexOf(“”),str.indexOf(“”+5),“”);
日志输出为

D/testit: <simp>example1</simp><val>example2</val><simp>example1</simp><val>example2</val><simp>example1</simp><val>example2</val>
D/testit:example1example2example2example2example2example2
编辑 正如Elsafar所说,
str.replaceAll(“.*”)
将起作用。

如下使用:

    String str = "<simp>example1</simp><op>example2</op><val>example2</val>";
    String garbage = str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5).trim();
    String newString = str.replace(garbage,"");
String str=“example1example2example2”;
字符串垃圾=str.substring(str.indexOf(“”),str.indexOf(“”+5).trim();
字符串newString=str.replace(垃圾“”);

我综合了所有答案,最终使用了:

st.replaceAll("<op>.*?<\\/op>","");
st.replaceAll(“*”,“);

谢谢大家的帮助

如果我没有弄错的话,这将只删除第一次出现的标记。@Dim use replaceAll()和“5”定义了“”的长度,而不是中间字符串长度。我相信仍然不起作用,因为indexOf也只匹配第一次出现的标记。我现在测试了它。它对我有用。请试用样品strings@Dim
长度为5个字符。+5将子字符串的末尾移动到该标记的末尾。此代码符合您的要求。很抱歉,未提及此代码,但长度不必为5“以/op(in)结尾”,长度必须为5。哦,对不起。明白了,这是XML,不是HTML。如果您有此
示例1example2example2
,会发生什么?谢谢,更新为XML。如果我有上面的例子,我想删除op中的所有内容,只得到example2,您可以使用它来匹配任何字符。
st.replaceAll("<op>.*?<\\/op>","");