【问题标题】:What will be the regex for replacing lowercase followed by period followed by uppercase?替换小写后跟句号后跟大写的正则表达式是什么?
【发布时间】:2014-06-03 10:40:13
【问题描述】:

我想替换字符串中出现的小写字母,后跟句点,后跟大写字母(没有任何空格)以包含空格。

例如:

...inconvenient.The...

转换成

...inconvenient. The...

在 Java 中有什么方法可以解决这个问题,可能使用正则表达式?

【问题讨论】:

  • 您应该发布一些代码以表明您至少尝试过。
  • @pandeSai 我对形成正则表达式一无所知。很快就学会了。

标签: java regex


【解决方案1】:

我假设你想在 lowercase 和 dot 之后插入一个空格字符,如果它后面跟着一个 大写..

String s = "foo.Bar and bar.Baz but not FOO.BAR or BAR.baz";
s = s.replaceAll("(?<=[a-z]\\.)(?=[A-Z])", " ");
System.out.println(s); //=> "foo. Bar and bar. Baz but not FOO.BAR or BAR.baz"

解释:

(?<=            # look behind to see if there is:
 [a-z]          # any character of: 'a' to 'z'
 \.             # '.'
)               # end of look-behind
(?=             # look ahead to see if there is:
 [A-Z]          # any character of: 'A' to 'Z'
)               # end of look-ahead

【讨论】:

    【解决方案2】:

    喜欢这样吗? s/([a-z])\.([A-Z])/$1. $2/

    【讨论】:

    • 鉴于问题被标记为 Java,人们很可能不会理解这一点(Java 不使用该语法来指定正则表达式)。
    【解决方案3】:

    就这个:

    result = subject.replace(/([a-z]\.)([A-Z])/g, "$1 $2");
    

    解释正则表达式

    (                        # group and capture to \1:
      [a-z]                  #   any character of: 'a' to 'z'
      \.                     #   '.'
    )                        # end of \1
    (                        # group and capture to \2:
      [A-Z]                  #   any character of: 'A' to 'Z'
    )                        # end of \2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多