-2

Simple regex question. I have a string in the following format:

string = """陣頭には見るも<RUBY text="いかめ">厳</RUBY>しい、厚い鎧姿の武士達が立つ。
 分厚い鉄甲、長大な太刀――彼らの<RUBY text="かも">醸</RUBY>し出す威圧感
は、一騎のみでも背後の兵全てに優る戦力たり得ると
いう事実を、何より雄弁に物語っている。"""

What is the regular expression to find the first occurance of <RUBY text="something">something</RUBY> and replace it with something like HELLO i.e

 陣頭には見るもHELLOしい、厚い鎧姿の武士達が立つ。
 分厚い鉄甲、長大な太刀――彼らの<RUBY text="かも">醸</RUBY>し出す威圧感
は、一騎のみでも背後の兵全てに優る戦力たり得ると
いう事実を、何より雄弁に物語っている。

I tried it with (<R(.*?)/RUBY>){0} but this didn't work.

string = re.sub("(\<R(.*?)\/RUBY>){0}", "HELLO", string)
print(string)
julius28
  • 49
  • 1
  • 5

1 Answers1

0

Can be done like this:

string = """陣頭には見るも<RUBY text="いかめ">厳</RUBY>しい、厚い鎧姿の武士達が立つ。
 分厚い鉄甲、長大な太刀――彼らの<RUBY text="かも">醸</RUBY>し出す威圧感
は、一騎のみでも背後の兵全てに優る戦力たり得ると
いう事実を、何より雄弁に物語っている。"""

try:
    first_match = re.findall(r'<RUBY text=.*</RUBY>', string)[0]
    parts = string.split(first_match)
    result = f'{parts[0]}HELLO{first_match.join(parts[1:])}'
except IndexError:
    result = string

print(result)

Result:

陣頭には見るもHELLOしい、厚い鎧姿の武士達が立つ。
 分厚い鉄甲、長大な太刀――彼らの<RUBY text="かも">醸</RUBY>し出す威圧感
は、一騎のみでも背後の兵全てに優る戦力たり得ると
いう事実を、何より雄弁に物語っている。
Michal Racko
  • 462
  • 2
  • 4