将字符串中的$..$替换为\(…\)在Python中。

huangapple go评论81阅读模式
英文:

Replace $..$ within a string with \(...\) in Python

问题

我有一个字符串在这里 'Let $[C | d]$ be $Star$'。

如何在上面的字符串中用\(...\)替换$..$。

结果应该是 'Let \([C | d]\) be \(Star\)'。

我可以用Python怎么做。

我已经尝试过如下:

import re
x = 'Let $[C | d]$ be $Star$'
y = re.sub(r'$.*?$', r'\\(.*?\\)', x)

但不起作用。

输出是 'Let \(.?\) be \(.?\)'。

英文:

I have a string here 'Let $[C | d]$ be $Star$'.

How to replace $..$ within the above string with \(...\).

The result should be 'Let \([C | d]\) be \(Star\)'.

How can I do it python.

I have tried as

import re
x = 'Let $[C | d]$ be $Star$'
y = re.sub(r'$.*?$', r'\\(.*?\\)', x)

but not working.

the output was 'Let \(.?\) be \(.?\)'

Ref : https://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud

答案1

得分: 1

这应该可以工作,以下是工作示例。

import re

string = 'Let $[C | d]$ be $Star$'

result = re.sub(r'$(.*?)$', r'\\(\\)', string)

print(result)

解释:

re.sub: 这是Python中re模块提供的用于执行正则表达式替换的函数。

r'\$(.*?)\$': 这是用于匹配字符串中所需模式 $..$ 的正则表达式模式。

  • \: 这是一个转义字符,确保后面的 $ 符号被视为字面字符,而不是正则表达式中的特殊字符。
  • \$(.*?)\$: 这将 $ 符号之间的内容捕获为一个组。.*? 是一个非贪婪匹配,捕获 $ 符号之间的任何字符(不包括换行符),但尽可能少。

r'(\1)': 这是匹配模式的替换模式。

  • (\1): 这使用反向引用来引用模式中捕获的第一个组。在这种情况下,它引用了 $ 符号之间捕获的内容。通过用括号括住 \1,我们指定替换应该具有格式 (...),捕获第一个组的内容。
英文:

It should work, here is the working example.

import re

string = 'Let $[C | d]$ be $Star$'

result = re.sub(r'$(.*?)$', r'\\(\\)', string)

print(result)

Explanation :

re.sub: This is the function provided by the re module in Python for performing regular expression substitution.<br>
r&#39;\$(.*?)\$&#39;: This is the regular expression pattern used for matching the desired pattern of $..$ in the string.

  • \: This is an escape character that ensures the following $ symbols are treated as literal characters, not as special characters in the regular expression.<br>
  • \$(.*?)\$: This captures the content between the $ symbols as a group. The .*? is a non-greedy match that captures any characters (except newline characters) between the $ symbols, but as few as possible.<br>

r&#39;(\1)&#39;: This is the replacement pattern for the matched pattern.

  • (\1): This uses a backreference to refer to the first captured group in the pattern. In this case, it refers to the content captured between the $ symbols. By surrounding \1 with parentheses, we specify that the replacement should have the format (...), capturing the content of the first group.

huangapple
  • 本文由 发表于 2023年7月17日 17:06:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定