将子字符串替换为一个整体
Substitute substrings as a whole
我有一个字符串,例如“31.5*q*L^2+831.5*M”。我想将字符串转换为 "\num{31.5}qL^2+\num{831.5}*M".
在 Julia 中,我已经尝试过:
str="31.5*q*L^2+831.5*M";
temp1=matchall(r"(\d*\.?\d+|\d+\.?\d*)",str);
str1=replace(str,temp1[1],"\num\{"*temp1[1]*"\}");
然后我得到了意想不到的结果:“\num{31.5}qL^2+8\num{31.5}*M”。
这个问题的解决方案是什么?
谢谢
replace(str,r"(\d*\.?\d+|\d+\.?\d*)",s->"\num\{$s\}")
可能是所需的解决方案。尽管它确实也替换了 L^2
中的指数 2。为避免这种替换,需要更改模式。
有关更多信息,请在 Julia 提示符 (REPL) 上尝试 ?replace
。上面的具体方法使用 Function
类型作为 r
参数。
可能 replace
对于简单的解决方案不够灵活,然后循环可以遍历每个数字并单独替换它。这更棘手。试试下面的代码:
str="31.5*q*L^2+831.5*M"
# The SLOW but more FLEXIBLE way
str1 = ""
lastpos = 1
for m in eachmatch(r"(?:^|[\+\*])(\d*\.?\d+|\d+\.?\d*)",str,false)
str1=str1*str[lastpos:m.captures[1].offset]*"\num\{"*m.captures[1]*"\}"
lastpos = m.captures[1].endof+m.captures[1].offset+1
end
str1 = str1*str[lastpos:end]
上面使用了eachmatch
和SubString
类型的内部结构。有时无法避免进入细节。
我有一个字符串,例如“31.5*q*L^2+831.5*M”。我想将字符串转换为 "\num{31.5}qL^2+\num{831.5}*M".
在 Julia 中,我已经尝试过:
str="31.5*q*L^2+831.5*M";
temp1=matchall(r"(\d*\.?\d+|\d+\.?\d*)",str);
str1=replace(str,temp1[1],"\num\{"*temp1[1]*"\}");
然后我得到了意想不到的结果:“\num{31.5}qL^2+8\num{31.5}*M”。
这个问题的解决方案是什么?
谢谢
replace(str,r"(\d*\.?\d+|\d+\.?\d*)",s->"\num\{$s\}")
可能是所需的解决方案。尽管它确实也替换了 L^2
中的指数 2。为避免这种替换,需要更改模式。
有关更多信息,请在 Julia 提示符 (REPL) 上尝试 ?replace
。上面的具体方法使用 Function
类型作为 r
参数。
可能 replace
对于简单的解决方案不够灵活,然后循环可以遍历每个数字并单独替换它。这更棘手。试试下面的代码:
str="31.5*q*L^2+831.5*M"
# The SLOW but more FLEXIBLE way
str1 = ""
lastpos = 1
for m in eachmatch(r"(?:^|[\+\*])(\d*\.?\d+|\d+\.?\d*)",str,false)
str1=str1*str[lastpos:m.captures[1].offset]*"\num\{"*m.captures[1]*"\}"
lastpos = m.captures[1].endof+m.captures[1].offset+1
end
str1 = str1*str[lastpos:end]
上面使用了eachmatch
和SubString
类型的内部结构。有时无法避免进入细节。