gpt4 book ai didi

replace - 定位字符串中的特定出现位置并替换它

转载 作者:行者123 更新时间:2023-12-02 10:01:31 24 4
gpt4 key购买 nike

我有一个包含多个 / 的字符串,我正在尝试将该字符串转换为 LaTeX 代码。基本上 (a)/(b) 变为 \\dfrac{a}{b}

困难在于(a)和/或(b)可能包含其他/

为了尊重括号平衡,我想从左到右替换 / ,并相应地替换它们周围的内容。我尝试过,但我不知道如何定位特定的 / 并替换。使用位置和长度参数似乎很复杂。

function ToFrac (s)
while s:find ("/") ~= nil
do

-- Replace : \dfrac{}{}/() -> \dfrac{\dfrac...}{}
if ( s:find ( '\\dfrac%b{}%b{}/%b()' , j ) ~= nil )
then
x,y,num,den = s:find( '(\\dfrac%b{}%b{})/(%b())' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(\\dfrac%b{}%b{})/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end

print ('### -- ', s)

-- Replace : ()/\dfrac{}{} -> \dfrac[}]{\dfrac...}
if ( s:find ( '(%b()/\\dfrac%b{}%b{}' ) ~= nil )
then
x,y,num,den = s:find( '((%b())/(\\dfrac%b{}%b{})' )
num = num:gsub( '.(.+).' , '%1' )
s = s:gsub( '((%b())/()\\dfrac%b{}%b{})',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
end

print ('### -- ', s)

-- Replace : ()/() -> \dfrac{}{}
if ( s:find ( '%b()/%b()' , 1 ) ~= nil )
then
x,y,num,den = s:find( '(%b())/(%b())' )
num = num:gsub( '.(.+).' , '%1' )
den = den:gsub( '.(.+).' , '%1' )
s = s:gsub( '(%b())/(%b())',
"\\dfrac{"..num.."}{"..den.."}" , 1 )
Done = true
end

print ('### -- ', s)

end -- while

return (s)

end

s = "((a)/(b))/(c)"
print (s, ToFrac(s))

s = "(a)/((b)/(c))"
print (s, ToFrac(s))

s = "(a)/(b)/(c)/(d))"
print (s, ToFrac(s))

s = "((a)/(b))/((c)/(d))"
print (s, ToFrac(s))

最佳答案

rpattiso想法的修改版本:

function to_frac(expr)
local t
return expr == '' and '' or (expr..'()'):gsub('(.-)(%b())',
function(prefix, subexpr)
local replace_with = ''
if not prefix:find'^%s*/%s*$' then
t, replace_with = {}, (not t and ''
or t[2] and '\\dfrac{'..t[1]..'}{'..t[2]..'}'
or '('..t[1]..')')..prefix
elseif t[2] then
t = {'\\dfrac{'..t[1]..'}{'..t[2]..'}'}
end
table.insert(t, to_frac(subexpr:sub(2,-2)))
return replace_with
end
)
end

print(to_frac' (a )/((b) / (c))') --> \dfrac{a }{\dfrac{b}{c}}
print(to_frac'((a)/((b)/(c)))/(e)') --> \dfrac{\dfrac{a}{\dfrac{b}{c}}}{e}
print(to_frac'(a)/(b)/(c)/(d)') --> \dfrac{\dfrac{\dfrac{a}{b}}{c}}{d}

关于replace - 定位字符串中的特定出现位置并替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31526394/

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