英文:
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
例如:
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's.
In the replacement using `-`
(?<=^a{1,100})a
[Regex demo](https://regex101.com/r/jeqTn3/1) | [Java demo](https://ideone.com/UXiTcq#stdin)
For example
System.out.println("aaabbaa".replaceAll("(?<=^a{0,100})a", "-"));
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 < cs.length && cs[i] == 'a'; ++i) {
cs[i] = '-';
}
String newStr = new String(cs);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论