简体   繁体   中英

Check if string is repetition of an unknown substring in javascript

I try to solve the same problem in javascript with regexp mentioned here: Check if string is repetition of an unknown substring

I translated the regex in the first answer to Javascript: ^(.+){2,}$ But it does not work as I expect:

'SingleSingleSingle'.replace(/^(.+){2,}$/m, '$1')  // returns 'e' instead of exptected 'Single'

What am I overlooking?

I currently have no explanation for why it returns e , but . matches any character and .{2,} basically just means "match any two or more characters".

What you want is to match whatever you captured in the capture group, by using backreferences:

/^(.+)\1+$/m

I just noticed that this is also what the answer you linked to suggests to use: /(.+)\\1+/ . The expression is exactly the same, there is nothing you have to change for JavaScript.

I think the reason why you get 'e' is that {2,} implies two or more repetitions of a match to the regex that preceeds it, in this case (.+) . {2,} does not guarantee that the repetitions match each other , only that they all qualify as a match for (.+) .

From what I can see (using Expresso ) it looks like the first match to (.+) is 'SingleSingleSingl' (due to greedy matching) and the second match is 'e'. Since capturing groups only remember their last match, that is why replace() is giving you back 'e'. If you use (.+?) (for non-greedy or reluctant matching) each individual character will match, but you will still only get the last one, 'e'.

Using a back reference, as Felix mentioned, is the only way that I know of to guarantee that the repetitions match each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM