【问题标题】:Removing full stops from String从字符串中删除句号
【发布时间】:2014-01-31 10:28:38
【问题描述】:

我正在尝试从字符串中删除句号。我已经尝试了以下

titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.", " "); 

不幸的是,这也删除了所有其他“点”。我的段落包括像 Jan.13, 2014 这样的日期,像 U.S 这样的词和像 2.2。如何只删除句号?

【问题讨论】:

  • 那么如何区分经期迟滞和正常经期?
  • 如果句号后的新行之间有空格,您可以利用它。
  • titleAndBodyContainer.replaceAll("\\.(\\s)", " $1"); 怎么样?这会将后跟空格字符的句号替换为空格后跟相同的空格字符。
  • @Zoltán:那 1 美元是多少?这是否意味着句号将被美元标记取代?
  • 不,这是一个捕获组。 $1 表示正则表达式中括号的内容。它就像一个正则表达式变量。 $1 代表第一个括号,$2 代表第二个括号,以此类推。为什么不试试呢?

标签: java regex string pattern-matching


【解决方案1】:

我愿意:

titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " "); 

【讨论】:

  • 嗨。这包含错误。 '无效的转义序列'
  • @GloryOfSuccess:我错过了空格的双倍。已更正,请参阅我的编辑。
【解决方案2】:

如果您的字符串(句子)在语法上是正确的,即句号后面的句子以大写字母开头,我认为您可以创建一个自定义方法来检查这样的句号,如果在句号之后有一个字符串的第一个字母大写。

【讨论】:

    【解决方案3】:

    您可以检查在. 之后是否有任何spacenewline

    您可以使用正则表达式:(\.(?=[\s\n\r]|$))

    代码:

     String input = "Unfortunately, this removed all other 'dots' as well. My paragraph includes dates like Jan.13, 2014 , words like U.S and numbers like 2.2. How can I remove only the full stops?\n"+"Somthing is there.\n"+"Hello someone . What is this something ? ";
    
     String REGEX = "(\\.(?=[\\s\\n\\r]|$))";
    
     String x=input.replaceAll(REGEX, " ");
    

    输出

    Unfortunately, this removed all other 'dots' as well My paragraph includes dates like Jan.13, 2014 , words like U.S and numbers like 2.2 How can I remove only the full stops?
    Somthing is there
    Hello someone  What is this something ? 
    

    DEMO

    【讨论】:

    • But even then... 而且我确信我可以提出更多例外。结论,这个任务不适合正则表达式。
    猜你喜欢
    • 2017-03-12
    • 2021-03-18
    • 2016-08-17
    • 2016-11-22
    • 2017-03-19
    • 2011-05-27
    • 2013-05-19
    • 2012-06-25
    • 1970-01-01
    相关资源
    最近更新 更多