javascript - 如何使用正则表达式(JS)查找不重复的字符串中的第一个字母?

标签 javascript regex

你能帮我写一个纯正则表达式来找到字符串中第一个不重复的字母吗?我想我可能需要使用负向前瞻和负向后向,但我认为 javascript 不支持向后看。

例如

'NUNUMUNN'        // expected output 'M'
'LOMING'          // expected output 'L'

我认为使用一般的字符串操作可以做到这一点,但我更喜欢纯正则表达式。

目前我的出发点是:

/(a-zA-Z).*?(?!\1)/.match('thestring');

但它不起作用。

最佳答案

扭转您的逻辑:首先匹配单词中所有重复的字母,然后匹配下一个字母 - 这就是您需要查看的字母。然后还有一些边缘情况需要考虑。

/\b(?:(?:([a-z])(?=[a-z]*\1))+(?!\1))?([a-z])(?![a-z]*\2)/ig

解释:

\b          # Start of word
(?:         # Start of non-capturing group (optional, see below)
 (?:        # Start of non-capturing group that matches...
  ([a-z])   # ...and captures any ASCII letter
  (?=       # if it's followed by
   [a-z]*   #  zero or more letters 
   \1       #  and the same letter again.
  )         # (end of lookahead assertion)
 )+         # Repeat at least once
 (?!\1)     # Assert that this letter doesn't follow immediately to avoid matching "AAA"
)?          # Make that group optional (in case there are no repeated letters in the word)
([a-z])     # Then match a letter and capture it in group 2.
(?![a-z]\2) # and make sure that letter doesn't immediately repeat either.

请注意,您需要查看匹配项的第 2 组才能获得结果 - 第 1 组将包含第一个非重复字母之前的所有内容。

测试一下 live on regex101.com .

关于javascript - 如何使用正则表达式(JS)查找不重复的字符串中的第一个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37153375/

相关文章:

javascript - 谷歌图表如何通过点击图例隐藏线条

regex - Sublime Text 正则表达式未检测到多行标签

javascript - 访问 iframe 外部的元素

javascript - 如何在 Javascript 正则表达式中匹配整个句子?

java - 查找 "can t"、 "haven t"等并添加撇号的正则表达式

C++ 正则表达式不匹配空格

Javascript 货币正则表达式

javascript - 如何使用 MongoDB/Meteor 处理 "relations"

javascript - 谷歌 OAuth gapi.auth.authorize X-Frame-Options : SAMEORIGIN

javascript - 无法使用来自 Angular2 Dart 应用程序的 CSS(CSS 垫片)