Java 在模式中提取一个动态值,然后将其放入另一个模式中
我有不同的字符串,形式为Java 在模式中提取一个动态值,然后将其放入另一个模式中,java,c#,regex,Java,C#,Regex,我有不同的字符串,形式为 Formula1(value) + Formula2(anotherValue) * 0.5 其中,Formula1和Formula2是常量。我想用正则表达式来 将初始字符串转换为 Formula1(value, constantWord) + Formula2(anotherValue, constantWord) * 0.5 这里的值,另一个值等是大写字母和数字字符串,可以由2或3字符组成 值s的正则表达式非常简单。但剩下的部分对我来说更难 我如何在C#或Jav
Formula1(value) + Formula2(anotherValue) * 0.5
其中,Formula1
和Formula2
是常量。我想用正则表达式来
将初始字符串转换为
Formula1(value, constantWord) + Formula2(anotherValue, constantWord) * 0.5
这里的值
,另一个值
等是大写字母和数字字符串,可以由2
或3
字符组成
值
s的正则表达式非常简单。但剩下的部分对我来说更难
我如何在C#或Java中做到这一点
示例:
Swipe(YN1) + Avg(DNA) * 0.5
Swipe(YN1, calculated) + Avg(DNA, calculated) * 0.5
期望的结果:
Swipe(YN1) + Avg(DNA) * 0.5
Swipe(YN1, calculated) + Avg(DNA, calculated) * 0.5
你可以试着向前看,向后看
匹配
[A-Z0-9]{2,3} - Capital letters or digits from 2 to 3 characters
最后,我们应该向前看,以找出右括号:
(?= ) - group, ahead: should appear before the match; will not be included into it
\s* - zero or more whitespaces (spaces, tabulations etc)
\) - closing parenthesis (escaped)
我们有
(?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*) -- Behind:
-- Letter, zero or more letters or digits, parenthesis
[A-Z0-9]{2,3} -- Value to match (2..3 capital letters or digits)
(?=\s*\) -- Ahead:
-- Closing parenthesis
请提供一些例子,好吗?我添加了一个例子,我认为它不起作用,“value”需要是一个regex,而不是所提供的例子中的
Replace
。这很有效,你能解释一下regex吗?即使有医生,我也不明白。非常感谢。
(?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-Z0-9]{2,3}(?=\s*\))
string source = @"Swipe(YN1) + Avg(DNA) * 0.5";
string argument = "calculate";
string result = Regex.Replace(
source,
@"(?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-Z0-9]{2,3}(?=\s*\))",
match => match.Value + $", {argument}");
Console.Write(result);
Swipe(YN1, calculate) + Avg(DNA, calculate) * 0.5