用java替换使用regexp的多个捕获组
我有这个要求-对于如下所示的输入字符串用java替换使用regexp的多个捕获组,java,regex,Java,Regex,我有这个要求-对于如下所示的输入字符串 8This8 is &reallly& a #test# of %repl%acing% %mul%tiple 9matched9 9pairs 我想剥离匹配的单词边界(匹配对为8或&或%等),并将产生以下结果 This is really a test of repl%acing %mul%tiple matched 9pairs 用于成对字符的字符列表可能会有所不同,例如8,9、%、#等,只有与每种类型的开头和结尾匹配的单词才会删除
8This8 is &reallly& a #test# of %repl%acing% %mul%tiple 9matched9 9pairs
我想剥离匹配的单词边界(匹配对为8或&或%等),并将产生以下结果
This is really a test of repl%acing %mul%tiple matched 9pairs
用于成对字符的字符列表可能会有所不同,例如8,9、%、#等,只有与每种类型的开头和结尾匹配的单词才会删除这些字符,并且单词中仍保留相同的字符
使用Java,我可以将模式设置为\\b8([^\\s]*)8\\b
并将替换为$1,以捕获和替换所有出现的8…8,但如何对所有类型的对执行此操作
我可以提供一个模式,例如\\b8([^\\s]*)8\\b | \\b9([^\\s]*)9\\b
。。以此类推,将匹配所有类型的匹配对*8,9,…),但如何指定“变量”替换组-
e、 g.如果匹配的是9…9,则替换者应为2美元
当然,我可以运行多个,每个都替换一对特定类型的鞋,但我想知道是否有更优雅的方式
还是有完全不同的方法来解决这个问题
谢谢。您可以使用下面的正则表达式,然后用组索引2中的字符替换匹配的字符
(?<!\S)(\S)(\S+)\1(?=\s|$)
说明:
(?负查找,断言匹配前面不会有非空格字符
捕获第一个非空格字符并将其存储到组索引1中(\\S)
捕获一个或多个非空格字符(\\S+)
指第一个捕获的组中的字符\\1
匹配后必须有空格或线锚的结尾(?=\\s |$)
- 这样可以确保字符串的第一个字符和最后一个字符必须相同。如果是这样,那么它将用组索引2中的字符替换整个匹配项
String s1 = "8This8 is &reallly& a #test# of %repl%acing% %mul%tiple 9matched9 9pairs";
System.out.println(s1.replaceAll("(?<!\\S)([89&#%])(\\S+)\\1(?=\\s|$)", "$2"));
String s1=“8This8实际上是%repl%acing%%mul%tiple 9 matched9对的测试”;
System.out.println(s1.replaceAll(“(?)?
如果您有许多分隔符,请使用此选项。谢谢。按照您和其他人的建议,使用back reference和capture groups to 2似乎已经解决了这个问题。我使用的是下面的(?@ssen,正是您得到的。更简化的(?)?
(?<!\\S)(\\S)(\\S+)\\1(?=\\s|$)
String s1 = "8This8 is &reallly& a #test# of %repl%acing% %mul%tiple 9matched9 9pairs";
System.out.println(s1.replaceAll("(?<!\\S)(\\S)(\\S+)\\1(?=\\s|$)", "$2"));
This is reallly a test of repl%acing %mul%tiple matched 9pairs
String s1 = "8This8 is &reallly& a #test# of %repl%acing% %mul%tiple 9matched9 9pairs";
System.out.println(s1.replaceAll("(?<!\\S)([89&#%])(\\S+)\\1(?=\\s|$)", "$2"));
(?<![a-zA-Z])[8&#%9](?=[a-zA-Z])([^\s]*?)(?<=[a-zA-Z])[8&#%9](?![a-zA-Z])
(?<![a-zA-Z])[^a-zA-Z](?=[a-zA-Z])([^\s]*?)(?<=[a-zA-Z])[^a-zA-Z](?![a-zA-Z])