Java正则表达式,用于更改字符串每个字中的每个第i个索引
我编写了一个regexJava正则表达式,用于更改字符串每个字中的每个第i个索引,java,regex,Java,Regex,我编写了一个regex\b\S\w(\S(?=)来查找单词中的每三个符号,并将其替换为“1”。现在我试着用这个表达,但真的不知道如何正确表达 Pattern pattern = Pattern.compile("\\b\\S\\w(\\S(?=.))"); Matcher matcher = pattern.matcher("lemon apple strawberry pumpkin"); while (matcher.find()) { System.out.print(match
\b\S\w(\S(?=)
来查找单词中的每三个符号,并将其替换为“1”。现在我试着用这个表达,但真的不知道如何正确表达
Pattern pattern = Pattern.compile("\\b\\S\\w(\\S(?=.))");
Matcher matcher = pattern.matcher("lemon apple strawberry pumpkin");
while (matcher.find()) {
System.out.print(matcher.group(1) + " ");
}
结果是:
m p r m
我怎么能用这个来做这样的字符串呢
le1on ap1le st1awberry pu1pkin
您可以使用以下内容:
"lemon apple strawberry pumpkin".replaceAll("(?<=\\b\\S{2})\\S", "1")
“柠檬苹果草莓南瓜”。replaceAll((?您可以使用类似以下内容:
"lemon apple strawberry pumpkin".replaceAll("(?<=\\b\\S{2})\\S", "1")
“柠檬苹果草莓南瓜”。replaceAll((?还有另一种方法可以访问匹配器的索引
像这样:
Pattern pattern = Pattern.compile("\\b\\S\\w(\\S(?=.))");
String string = "lemon apple strawberry pumpkin";
char[] c = string.toCharArray();
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
c[matcher.end() - 1] = '1';////// may be it's not perfect , but this way in case of you want to access the index in which the **sring** is matches with the pattern
}
System.out.println(c);
还有另一种方法可以访问匹配器的索引
像这样:
Pattern pattern = Pattern.compile("\\b\\S\\w(\\S(?=.))");
String string = "lemon apple strawberry pumpkin";
char[] c = string.toCharArray();
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
c[matcher.end() - 1] = '1';////// may be it's not perfect , but this way in case of you want to access the index in which the **sring** is matches with the pattern
}
System.out.println(c);
你真的需要在这里使用正则表达式吗?是的。这是我的任务。你真的需要在这里使用正则表达式吗?是的。这是我的任务。谢谢。这是我需要的。谢谢。这是我需要的。