java如何创建正则表达式来替换已知字符串,同时保持可选参数不变?
我已经试了一段时间了,但还没弄对: 在Java中,我试图创建一个正则表达式来匹配和替换字符串中的一个(对我来说是已知的)字符串,同时保持可选参数不变
输入示例:
{067e6162-3b6f-4ae2-a171-2470b63dff00}
{067e6162-3b6f-4ae2-a171-2470b63dff00,number}
{067e6162-3b6f-4ae2-a171-2470b63dff00,number,integer}
{067e6162-3b6f-4ae2-a171-2470b63dff00,choice,1#one more item|1<another {067e6162-3b6f-4ae2-a171-2470b63dff00,number,integer} items}
(请注意,上一个示例包含对同一输入字符串的嵌套引用)。
格式总是将要替换的字符串括在花括号中{...}
,但带有逗号分隔参数的可选列表
我想用数字替换输入字符串,例如,对于上述输入字符串,结果应该是:
{2}
{2,number}
{2,number,integer}
{2,choice,1#one more item|1<another {2,number,integer} items}
理想情况下,我希望有一个足够灵活的正则表达式,可以(几乎)将任何字符串作为要替换的模式来处理,所以不仅要像上面那样处理UUID类型的字符串,还要像这样处理:
A test string with {the_known_input_value_to_be_replaced,number,integer} not replacing the_known_input_value_to_be_replaced if its not in curly brackets of course.
最终应为,例如:
A test string with {3,number,integer} not replacing the_known_input_value_to_be_replaced if its not in curly brackets of course.
请注意,仅当输入字符串位于花括号中时,才应进行替换。 在Java中,我将能够在运行时构造模式,详细考虑待替换字符串
我尝试了\{(067e6162-3b6f-4ae2-a171-2470b63dff00)(,?.*)\}
(还没有java转义)和\{(+?)(,?.*)\}
等更通用的方法,但它们都做得不对
非常感谢regex忍者的任何建议:)
# 1 楼答案
如果已知的旧字符串总是出现在
{
之后,则可以使用如果在花括号内确实有多个已知字符串(并且没有要处理的转义花括号),可以使用以下代码:
结果:
067e6162-3b6f-4ae2-a171-2470b63dff00 is outside {{NEW_KEY,choice,NEW_KEY,1#one more item|1<another {NEW_KEY,number,NEW_KEY,integer} items} 067e6162-3b6f-4ae2-a171-2470b63dff00 is outside
replaceInBalancedSubstrings
方法如下所示:见IDEONE demo
这段代码只处理平衡(嵌套)花括号内的子字符串中的替换