Make at least one group mandatory

I have a question about regular expressions in Java, although I think this may apply to other languages ​​as well.

I have a regex for parsing time from a field where the user can enter something like 4d 8h 42m . Of course, I want to make it as flexible as possible so that the user is not required to enter all numbers (and just enter 15h ).

My regular expression is quite satisfactory at this point: (?:([\d]+)d)?[\s]*(?:([\d]+)h)?[\s]*(?:([\d]+)m)?

Now my problem is that it will also correspond to an empty string, although I would like it to be filled with at least one block of time.

The current solution would be arbitrary to choose one of them as mandatory, but I am not satisfied with this, since the required field is what I am trying to avoid.

Also, I'm not interested, as I will have to test groups when analyzing a regular expression, instead of just accessing group (1) for several days, group (2) for several hours, ... (This is what I think about when it comes to or: (?:([\d]+)d[\s]*(?:([\d]+)h)?[\s]*(?:([\d]+)m)?|(?:([\d]+)d)?[\s]*([\d]+)h[\s]*(?:([\d]+)m)?|(?:([\d]+)d)?[\s]*(?:([\d]+)h)?[\s]*([\d]+)m) to understand how days are obligatory or hours are obligatory or minutes are obligatory).

So, how can I change my regular expression to make sure that at least one of my groups that are not captured right now is not empty, be it days, hours or minutes?

+4
source share
2 answers

You can use the search confirmation to make sure that at least one of d h or m appears.

 (?=.*[mhd])(?:(\d+)d)?\s*(?:(\d+)h)?\s*(?:(\d+)m)? 
+4
source

As suggested by OmnipotentEntity, you can use a positive prediction to determine if number (a) is followed by the next d , m or h .

Another way to write could be:

 (\d+(?=[dhm])[dhm]\s*){1,3} 

This will correspond to the following:

 4d 8h 42m 3d 15h 28m 12d 24m 2h 55m 7d 11h 24m 5d2h5m 
+2
source

Source: https://habr.com/ru/post/1447151/


All Articles