简体   繁体   English

替换字符串中的字符,Java

[英]Replacing characters in a string, Java

I have a string like s = "abc.def..ghi" . 我有一个像s = "abc.def..ghi"的字符串。 I would like to replace the single'.' 我想取代单曲。 with two '.'s. 有两个“。”。 However, s.replace(".", "..") yields "abc..def....ghi". 但是, s.replace(".", "..")产生“ abc..def .... ghi”。 How can I get the correct behaviour? 如何获得正确的行为? The output I'm looking for is s = "abc..def..ghi" . 我正在寻找的输出是s = "abc..def..ghi"

Replace the dot only when it's surrounded by two characters 仅当点被两个字符包围时才替换

String foo = s.replaceAll("(\\w)\\.(\\w)", "$1..$2");

Or as @Thilo commented, only if it's surrounded by two non dots 或如@Thilo所评论,仅当它被两个非圆点包围时

String foo = s.replaceAll("([^.])\\.([^.])", "$1..$2");

And to replace the single dot with two dots even if the dot is at the beginning/end of the string, use a negative lookahead and lookbehind: (Example String: .abc.def..ghi. will become ..abc..def..ghi.. ) 而且,即使点位于字符串的开头/结尾,也要用两个点替换单个点,请使用负数前瞻和后向:(示例字符串: .abc.def..ghi.将变为..abc..def..ghi..

String foo = s.replaceAll("(?<!\\.)\\.(?!\\.)", "..");

If you don't know how to do it using regex then use StringTokenizer to split the String and again concatenate with .. . 如果您不知道如何使用正则表达式,则使用StringTokenizer拆分String并再次与..串联。

Code: 码:

public static void main(String[] args) {
    String s = "abc.def..ghi";
    StringTokenizer s2 = new StringTokenizer(s, ".");
    StringBuilder sb = new StringBuilder();


    while(s2.hasMoreTokens())
    {
        sb.append(s2.nextToken().toString());
        sb.append("..");
    }
    sb.replace(sb.length()-2, sb.length(), ""); // Just delete an extra .. at the end

    System.out.println(sb.toString());

}

I know that the code is big compared to one line regex but I posted it in case if you are having any trouble with regex. 我知道代码与一行正则表达式相比是很大的,但是我发布了它,以防万一您遇到正则表达式的麻烦。 If you think it is slower than the accepted answer, I did a start and end time with System.currentTimeMillis() and I got mine faster. 如果您认为它比接受的答案慢,那么我使用System.currentTimeMillis()进行了开始和结束时间,并且得到的速度更快。 I don't know if there are any exceptions to that test. 我不知道该测试是否有任何例外。

Anyway, I hope it helps. 无论如何,我希望它会有所帮助。

Use look arounds: 使用环顾四周:

str = str.replaceAll("(?<!\\.)\\.(?!\\.)", "..")(

The regex reads as "a dot, not preceded by a dot, and not followed by a dot". 正则表达式的读法是“一个点,前面没有点,后面没有点”。 This will handle the edge cases of a dot being at the start/end and/or surrounded by literally any other character. 这将处理点的开始/结束和/或实际上由任何其他字符包围的点的边缘情况。

Because look arounds don't consume input, you don't have to sully yourself with back references in the replacement term. 由于环顾四周不会消耗任何输入,因此您不必在替换术语中用向后引用来嘲笑自己。

s.replace("...","..");
s.replace("....","..");

Depends on input possibilities.. 取决于输入的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM