簡體   English   中英

結束符防止Java從字符串中刪除子字符串

[英]End line characters prevent java from removing substrings from a string

我想從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無法正常工作嗎?

更新:

它明確地是我刪除它們的結束行字符,並且可以工作。 但是我仍然想保留我的結束行字符,我有什么辦法可以做到這一點?

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

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

String s2= s.replaceAll("<b>.*?</b>", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM