我有一个需要使用regex替换特定字符的文件。我有以下格式的字符串:
1234 4215 "aaa.bbb" 5215 1524我需要把句号换成冒号。我知道这些句点总是包含在引号中,所以我需要一个正则表达式来查找以'"‘开头,’结尾的子字符串,并包含“”。“并替换".“使用":“。有没有人能说点什么?
发布于 2015-07-18 00:06:46
您可以使用:
str = str.replaceAll("\\.(?!(([^"]*"){2})*[^"]*$)", ":");如果点在双引号内,这个正则表达式将通过先行查找来确定点后面没有偶数个引号。
发布于 2015-07-18 00:23:22
更新
仔细考虑之后,您的问题说" period (s)“可能不止一个句点用双引号引起来。
下面是介绍该场景的一种方法
public static void main(String[] args) throws Exception {
String str = "1234 \"aaa.bbb\" \"a.aa.b.bb\" 5215 1524 \"12.345.123\" \".sage.\" \".afwe\" \"....\"";
// Find all substrings in double quotes
Matcher matcher = Pattern.compile("\"(.*?)\"").matcher(str);
while (matcher.find()) {
// Extract the match
String match = matcher.group(1);
// Replace all the periods with colons
match = match.replaceAll("\\.", ":");
// Replace the original matched group with the new string
str = str.replace(matcher.group(1), match);
}
System.out.println(str);
}结果:
1234 "aaa:bbb" "a:aa:b:bb" 5215 1524 "12:345:123" ":sage:" ":afwe" "::::"在测试@anubhava模式之后,他的模式产生了相同的结果,因此他的简单性得到了更多的信任(+1)。
老答案
您可以在String.replaceAll()中尝试此模式
"\"([^\\.]*?)(\\.)([^\\.]*?)\""通过替换
"\"$1:$3\""这实际上是在双引号之间将内容捕获到组(1-3)中。
并替换为"{Group 1}:{Group 3}“
public static void main(String[] args) throws Exception {
String str = "1234 4215 \"aaa.bbb\" 5215 1524 \"12345.123\" \"sage.\" \".afwe\" \".\"";
System.out.println(str.replaceAll("\"([^\\.]*?)(\\.)([^\\.]*?)\"", "\"$1:$3\""));
}结果:
1234 4215 "aaa:bbb" 5215 1524 "12345:123" "sage:" ":afwe" ":"https://stackoverflow.com/questions/31479977
复制相似问题