0

我想从java中的字符串中删除以特定文本开头并以特定文本结尾的所有子字符串(示例)

所以我想删除

<tag> And everything in between  </endTag>

我在标签之间有结束行字符。我想删除多项内容,但其中一项以

WHAT DO YOU WANT TO KNOW ?

并以

<end>

我努力了

text = text.replaceAll("WHAT DO YOU WANT TO KNOW \\?.*?<end>", "");

但它没有用

text = text.replaceAll("CHAPTER 18" , ""); works

这是我要替换的一大块文本(只是一个示例,还有更多示例)(这是一本人类性行为书籍的作品,所以如果您感到不舒服,请不要阅读它,但我觉得里面没有任何东西这是不合适的)

 (Tons of text here) WHAT DO YOU WANT TO KNOW ?
    Most kids today know all about sex at an early 
    age. So why are people so uptight about 
    showing nudity on television? What do they 
    think it will do to their kids?
    Even in a society like ours, which has begun to discuss sex 
    more openly, it is still a diffi cult subject for children to 
    understand. Many parents believe that it is their job to 
    introduce the topic to their children, to explain it to them, 
    and to teach their children whatever values the parents 
    believe are appropriate. This may be undermined when 
    children see fairly uncensored sexuality on television, which 
    is usually shown without any discussion of values and 
    without any way to address the children’s questions about 
    what they are seeing. In the accompanying Sex in Real Life, 
    “Generation M,” we talk about research on the media 
    consumption habits of children and teenagers.
    REALResearch > Studies have shown that people are less 
    likely to remember the brand name of a product in an ad with sex 
    and violence than in an ad without (BUSHMAN & BONACCI, 2002).
    <end> (tons of text here) 

可能是我的文本格式器不允许 replaceAll 工作的方式吗?

更新:

它绝对是我删除它们的结束行字符并且它有效。但是我仍然想保留我的结束行字符有什么办法可以做到吗?

4

2 回答 2

2
String s = "text that needs WHAT DO YOU WANT TO KNOW ? " +
        "more text that needs deletion <end>to stay";
System.out.println(s.replaceAll("(?s)WHAT DO YOU WANT TO KNOW \\?.*?<end>", ""));

输出:

text that needs to stay
于 2012-05-17T14:10:31.703 回答
1

您可以在 Java 中使用正则表达式。使用正则表达式的方法之一是 String 的replaceAll方法:

String s2= s.replaceAll("<b>.*?</b>", "");
于 2012-05-17T14:13:26.507 回答