gpt4 book ai didi

java - 提取模式中的动态值并将其放入另一个模式中

转载 作者:行者123 更新时间:2023-12-02 10:46:53 28 4
gpt4 key购买 nike

我有不同形式的字符串

Formula1(value) + Formula2(anotherValue) * 0.5

哪里Formula1Formula2常数。我想使用正则表达式来将初始字符串转换为

Formula1(value, constantWord) + Formula2(anotherValue, constantWord) * 0.5

这里value , anotherValue等是由大写字母数字组成的字符串,可以由2组成。或3字符。

value 的正则表达式s 很简单。但剩下的部分对我来说比较困难。

如何在 C#Java 中做到这一点?

示例:

Swipe(YN1) + Avg(DNA) * 0.5

期望的结果:

Swipe(YN1, calculated) + Avg(DNA, calculated) * 0.5

最佳答案

您可以尝试向前看向后看

(?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-Z0-9]{2,3}(?=\s*\))

正则表达式详细信息:

我们有感兴趣的简单匹配[A-Z0-9]{2,3} - 从23 大写字母数字。但此匹配应该位于公式之后(例如Swipe(Formula1())和之前 )。假设公式是一个标识符(从字母开始,可以包含字母或数字),我们可以输入

(?<=  )      - group, behind: should appear before the match; will not be included into it
[A-Za-z] - one letter (Formula1)
[A-Za-z0-9]* - letters or digits, zero or more
\s* - whitespaces (spaces, tabultalions) - zero or more

匹配

[A-Z0-9]{2,3} - Capital letters or digits from 2 to 3 characters 

最后,我们应该在 oreder 中向前查找右括号:

(?= ) - 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

最终模式

(?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-Z0-9]{2,3}(?=\s*\))

参见https://www.regular-expressions.info/lookaround.html了解详情

C#代码:

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

关于java - 提取模式中的动态值并将其放入另一个模式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477573/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com