简体   繁体   English

我正在尝试创建一个正则表达式来搜索字符串中重复的字母

[英]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.

相关问题 我正在尝试使用JavaScript控制器中的正则表达式验证字符串? - I am trying to validate a string with a regular expression in the javascript controller? 我正在尝试使用JavaScript中的正则表达式验证日期,但无法正常工作? - I am trying to validate a date with a regular expression in JavaScript but it is not working correctly? 我将使用什么正则表达式来检索此字符串后面的数字? - what regular expression would I use to retrieve the digits that follow this string? JavaScript 正则表达式在字符串中重复元素匹配 - JavaScript Regular Expression to repeat element match in string 我如何制作一个正则表达式,这意味着/某个字符串/后跟换行符? - How would I make a regular expression that would mean /some string/ either followed by a line break or not? 使用Javascript我如何搜索字符串中的前三个字母,看看它们是否匹配“ABC”? - With Javascript how would I search the first three letters in a string and see if they match “ABC”? Javascript .search()问题Uncaught SyntaxError:无效的正则表达式:/ * /:无需重复 - Javascript .search() issue Uncaught SyntaxError: Invalid regular expression: /*/: Nothing to repeat 正则表达式检测到字符串同时包含字母和数字 - Regular expression detect that string contains both letters and numbers 包含一个或多个指定字母的字符串的Javascript正则表达式 - Javascript Regular Expression for a string that contains one or more of specified letters 在match的正则表达式上指示的Javascript match()字符串字母 - Javascript match() string letters which are indicated on regular expression of match
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM