Hello
I want to create a condition that matches the same word repeatedly.
Example)
@Apple @Tangerine @Banana @Apple @ grape
If there is a string called
that starts with @ and ends with a half-width space in this string,
How should I write the condition that a string of the same group matches more than once?
In the case of the example, @Apple appears twice, so I would like to determine that @Apple matches.
Thank you for your cooperation.
regular-expression
The writing style depends on the regular expression engine, but can be achieved with back reference of the captured group.
Example: @Apple@Tangerine@Banana@Apple@Vine
Regular expression:(@\S+).+\1
Regular Expression Checker
This answer is an application of similar answer.
\w
may not match Japanese depending on the regular expression engine, so we used \S
(all characters except blank characters) in this answer.
By the way, I had a hard time verifying this answer because I couldn't get the results as expected in the example you asked.
This is because the first @ apple has full-width spaces and the second @ apple has full-width spaces.
Computers and regular expression engines treat full-width and half-width characters as completely different characters, so I advise you not to confuse full-width and half-width characters when coding.
>>import re
>>>text='@Apple@Tangerine@Banana@Apple@Vine'
>>re.findall(r'(@\w+)(?=.+\1\b), text)
["@Apple"]
>>>text='@Apple@Tangerine@Banana@Apple@Vine@Banana'
>>re.findall(r'(@\w+)(?=.+\1\b), text)
["@Apple", "@Banana"]
>>>text='@Apple@Tangerine@Banana@Apple@Vine@BananaChocolate'
>>re.findall(r'(@\w+)(?=.+\1\b), text)
["@Apple"]
© 2024 OneMinuteCode. All rights reserved.