Java替换字符串中的初始字符并保持长度不变

huangapple go评论89阅读模式
英文:

Java replace initial characters in String and preserve length

问题

我正在寻找解决方案(Java),以替换多个字符的初始出现,用相同数量的其他字符来代替,例如,如果字符'a'应替换为'-',那么我期望的结果是:

aaabbaa  -> ---bbaa
aaxxaab  -> --xxaab
xaaaaax  -> xaaaaax

我尝试过类似以下的方法:

"aaabbaa".replaceAll( "^[a]+", "-")        // -bbaa
"aaabbaa".replaceAll( "(?=^[a]+)", "-")    // -aaabbaa

如果可能的话,我更倾向于使用正则表达式或一行代码。

你有什么提示呢?

祝好,
Annie

英文:

I'm looking for solution (Java) to replace the initial occurrences of multiple character with the same number of other character, for example if 'a' should be replaced with '-', than I expect:

aaabbaa  -> ---bbaa
aaxxaab  -> --xxaab
xaaaaax  -> xaaaaax

I've tried something like:

"aaabbaa".replaceAll( "^[a]+", "-")        // -bbaa
"aaabbaa".replaceAll( "(?=^[a]+)", "-")    // -aaabbaa

If possible, I prefer regex or oneliner.

Do you have any hints?

regards,
Annie

答案1

得分: 4

如果使用Java 9+,请使用replaceAll的lambda重载:

import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String res = Pattern
            .compile("^a+")
            .matcher("aaabbb")
            .replaceAll(m -> "-".repeat(m.group().length()));
        System.out.println(res); // => ---bbb
    }
}
英文:

If using Java 9+, use the lambda overload for replaceAll:

import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String res = Pattern
            .compile("^a+")
            .matcher("aaabbb")
            .replaceAll(m -> "-".repeat(m.group().length()));
        System.out.println(res); // => ---bbb
    }
}

答案2

得分: 4

Java支持在回顾后面的表达式中进行有限的重复您可以匹配从字符串开头开始的左侧断言这些断言只是'a'

在替换中使用 `-`

```java
(?<=^a{1,100})a

正则表达式演示 | Java演示

例如:

System.out.println("aaabbaa".replaceAll("(?<=^a{0,100})a", "-"));

输出:

---bbaa

<details>
<summary>英文:</summary>

Java supports finite repetition in a lookbehind. You could match a asserting what is on the left from the start of the string are only a&#39;s.

In the replacement using `-`

    (?&lt;=^a{1,100})a

[Regex demo](https://regex101.com/r/jeqTn3/1) | [Java demo](https://ideone.com/UXiTcq#stdin)

For example

    System.out.println(&quot;aaabbaa&quot;.replaceAll(&quot;(?&lt;=^a{0,100})a&quot;, &quot;-&quot;));

Output

    ---bbaa

</details>



# 答案3
**得分**: 1

使用 `char[]`:

```java
char[] cs = str.toCharArray();
for (int i = 0; i < cs.length && cs[i] == 'a'; ++i) {
  cs[i] = '-';
}
String newStr = new String(cs);
英文:

Use a char[]:

char[] cs = str.toCharArray();
for (int i = 0; i &lt; cs.length &amp;&amp; cs[i] == &#39;a&#39;; ++i) {
  cs[i] = &#39;-&#39;;
}
String newStr = new String(cs);

huangapple
  • 本文由 发表于 2020年8月14日 21:30:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63413761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定