in a regular expression, a way of writing in which the same word matches n or more iterations

Asked 2 months ago, Updated 2 months ago, 373 views

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

2022-11-21 04:17

2 Answers

The writing style depends on the regular expression engine, but can be achieved with back reference of the captured group.

Example: @[email protected]@[email protected]@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.


2022-11-21 04:45

>>import re

>>>text='@[email protected]@[email protected]@Vine'
>>re.findall(r'(@\w+)(?=.+\1\b), text)
["@Apple"]

>>>text='@[email protected]@[email protected]@[email protected]'
>>re.findall(r'(@\w+)(?=.+\1\b), text)
["@Apple", "@Banana"]

>>>text='@[email protected]@[email protected]@[email protected]'
>>re.findall(r'(@\w+)(?=.+\1\b), text)
["@Apple"]


2022-11-21 14:52

If you have any answers or tips


© 2023 OneMinuteCode. All rights reserved.