0

This is an example of what the regex would and wouldn't match:

# Matches
AAAA: aaaa
# Matches
ABCD: abcd
# Doesn't match
AAAA: abcd
# Doesn't match
AAAA: AaAa

How can I accomplish this?

I found this, but it doesn't work for matches because \L transforms the matches in the replace. Besides, \L seems to be only available in PHP and not in Javascript:

This works, but only when the case-insensitive option is set and it matches the last example:

(\w+): \1
Adrian
  • 1,558
  • 1
  • 13
  • 31
  • regex is probably not the best way to do this. Do you need to use regex or can you use whatever language you are using? – depperm Jan 30 '23 at 17:21
  • @depperm I don't even need to do this, I just wondered. I was using VSCode and I had this javascript object with keys uppercase and values their lowercase version and I wanted to know if this is possible, I don't really need this. – Adrian Jan 30 '23 at 17:23

1 Answers1

1

You might be able to use case-sensitivity switch and lookahead. eg.

\b(?=[A-Z]+:\s*[a-z]+)(?i)(\w+):\s*\1\b

or

\b(?=\p{Lu}+:\s*\p{Ll}+)(?i)(\p{L}+):\s*\1\b

Essentially you use 2 regexes at once.

  • The first (i.e. everything within (?=...)) asserts that the first word is all uppercase ([A-Z]+ or \p{Lu}+) and that the second word is all lowercase ([a-z]+ or \p{Ll}+).
  • Then you turn on case-insensitivity with (?i).
  • Then the second regex looks for 2 words that are equal (ignoring case).

The \b prevent matches on input like: xxAAA: aaayy

Note: As the question mentioned VSCode, this answer uses .NET-style regex and assumes that the i modifier is initially turned off but can be toggled. However, I don't think this is possible in ECMAScript ("flags are an integral part of a regular expression. They cannot be added or removed later").

Adrian
  • 1,558
  • 1
  • 13
  • 31
jhnc
  • 11,310
  • 1
  • 9
  • 26
  • 1
    Essentially you use 2 regexes at once. The first one (Everything within `(?=...)` checks that the first word is all uppercase and the second word is all lowercase. Then you turn case-insensitiveness with `(?i)`. The second regex checks with case-insensitive turned on that the 2 words are equal. I can't edit your question to add this clarification because according to StackOverflow "There are too many pending edits". Please edit your post to clarify how your regex works and I'll accept it. Also you might want to clarify you have to use this regex with the `i` modifier turned off to turn it on. – Adrian Jan 30 '23 at 18:56
  • @Adrian No idea why you get that message. Thanks for the improvements. – jhnc Jan 30 '23 at 20:09