4

I'm porting some Lua code to JS and I haven't worked with Lua so far. There's the Lua pattern "^([^aeiouàèéêíòóôúïü]*)(.-)$" and I found the following explanation for the hyphen here:

- Match the previous character (or class) zero or more times, as few times as possible.

I'm trying to figure out what the equivalent as a regular expression would be. Also I don't understand why this is needed in the first place - wouldn't ending in (.*)$ suffice?

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
  • "wouldn't ending in (.*)$ suffice?" It'd be equivalent, but I guess `.-` expresses some intent as "Match as few characters as possible" – DarkWiiPlayer Jul 01 '19 at 13:44

2 Answers2

3

In Java, .- is actually equivalent of [\s\S]*? or (?s).*?, or - to play it safe - (?s:.*?), because . in Lua patterns matches any char (including line break chars) and - is the lazy (non-greedy) quantifier that matches 0 or more chars, i.e. *? in regular NFA regex.

See Lua patterns:

. all characters

And then

The `+´ modifier matches one or more characters of the original class. It will always get the longest sequence that matches the pattern.

The modifier `*´ is similar to `+´, but it also accepts zero occurrences of characters of the class...

Like `*´, the modifier `-´ also matches zero or more occurrences of characters of the original class. However, instead of matching the longest sequence, it matches the shortest one.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Actually, that pattern is pretty much equivalend to the corresponding regex in many languages. Javascript seems to not have the - quantifier, but you should be able to replace it with .* and it should still work.

Try "^([^aeiouàèéêíòóôúïü]*)(.*)$"

Of course, you can also test this in the Lua REPL:

Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> orig = '^([^aeiou]*)(.-)$'
> modif = '^([^aeiou]*)(.*)$'
> ("jhljkhaaaasjkdf"):match(orig)
jhljkh  aaaasjkdf
> ("jhljkhaaaasjkdf"):match(modif)
jhljkh  aaaasjkdf
> -- QED
DarkWiiPlayer
  • 6,871
  • 3
  • 23
  • 38