[英]I am trying to create a regular expression that would search for letters that repeat in a string
Eg "asdoekrikkm", i want a regex that will match the "k" because it repeats in the string.例如“asdoekrikkm”,我想要一个匹配“k”的正则表达式,因为它在字符串中重复。 I am trying to use string.match(regex) to do that, but i am not sure how to structure the regex.我正在尝试使用 string.match(regex) 来做到这一点,但我不确定如何构建正则表达式。
You can use a capture group and a back reference:您可以使用捕获组和反向引用:
const match = "asdoekrikkm".match(/(.)\1/)[1]; console.log(match);
(.)
finds any character and stores it in a capture group. (.)
找到任何字符并将其存储在捕获组中。 \1
is a back reference to the first character. \1
是对第一个字符的反向引用。 (.)\1
searches for two same consecutive characters. (.)\1
搜索两个相同的连续字符。 .match
returns an array with the full match (both consecutive characters) and the the capture group. .match
返回一个包含完整匹配(两个连续字符)和捕获组的数组。 "asdoekrikkm".match(/(.)\1/)[0]
is the full match (two characters) and "asdoekrikkm".match(/(.)\1/)[1]
is the capture group (one character). "asdoekrikkm".match(/(.)\1/)[0]
是完整匹配(两个字符), "asdoekrikkm".match(/(.)\1/)[1]
是捕获组(一个字符).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.