'I want to simplify this regex, /^data$|^data-/,what should I do?

I want to use regex to match data or data-a or data-b or data-abcdefg.

 /^data$|^data-/

I feel like it could be simplified, but I'm not good at this。



Solution 1:[1]

If you want to simplify the current pattern to get the same matches as that you will get with you current pattern, you can make the hyphen optional. Note that this will give you a partial match.

^data-?

Regex demo

If you want to match the whole line, you can optionally match a group (in this example a non capture group if that is supported) that starts with a hyphen and then match the rest of the line:

^data(?:-.*)?

Regex demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 The fourth bird