The string that matches the duration of hour, minute, and second (HMS)

There is a need to extract the digits before h, m, and s into their own groups. The objective is to capture all three groups if possible, but if one or two groups are missing, then the last group(s) should be captured.

Currently, the regex

/(\d+)(?=h)|(\d+)(?=m)|(\d+)(?=s)/g
is generating 12 matches with a single group in each match, as demonstrated in the image below and in this regex101.

https://i.sstatic.net/ZYUMY.png

However, the goal is to have 7 matches with different group configurations. The first match should contain 3 separate groups, the following three matches should have 2 groups each, and the last three matches should contain 1 group each.

Therefore, the desired output is as follows:

  1. Match 1: 11h22m33s
    1. Group 1: 11
    2. Group 2: 22
    3. Group 3: 33
  2. Match 2: 11h22m
    1. Group 1: 11
    2. Group 2: 22
  3. Match 3: 11h33s
    1. Group 1: 11
    2. Group 2: 33
  4. Match 4: 22m33s
    1. Group 1: 22
    2. Group 2: 33
  5. Match 5: 11h
    1. Group 1: 11
  6. Match 6: 22m
    1. Group 1: 22
  7. Match 7: 33s
    1. Group 1: 33

Edit

The test strings could be embedded within other text, like 08:00 + 11h. Refer to https://regex101.com/r/RWA9Oy/1

Answer №1

To ensure that the entire string matches the specified pattern, you can utilize:

^(?!$)(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$

For a demonstration, check out the regex demo.

If you need to extract these patterns from longer texts, you can employ:

\b(?=\w)(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?\b(?!\w)

Refer to this regex demo for further details.

Key Details:

  • ^ - marks the start of the string
  • (?!$) - ensures that the string does not end at the beginning (i.e., it cannot be empty)
  • \b(?=\w) - a word boundary where the adjacent character is a word character (letter, digit, or _)
  • (?:(\d+)h)? - an optional group capturing one or more digits (saved in Group 1) followed by a 'h'
  • (?:(\d+)m)? - an optional group capturing one or more digits (saved in Group 2) followed by an 'm'
  • (?:(\d+)s)? - an optional group capturing one or more digits (saved in Group 3) followed by an 's'
  • $ - denotes the end of the string
  • \b(?!\w) - a word boundary where the next character is not a word character, or it's at the end of the string

If you want to allow spacing between components, you can include \s*:

^(?!\s*$)\s*(?:(\d+)\s*h\s*)?(?:(\d+)\s*m\s*)?(?:(\d+)\s*s)?\s*$

Alternatively, for partial matching:

\b(?=\w)(?:(\d+)\s*h\s*)?(?:(\d+)\s*m\s*)?(?:(\d+)\s*s)?\b(?!\w)

Take a look at this regex demo and another regex demo for more examples.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying or concealing fields through Javascript depending on the category type of the results item

I am facing an issue with displaying certain fields in each individual property search result based on the property type. For example, if a property is classified as Land, I do not want the bedrooms and bathrooms fields to be visible, but if it is a Villa, ...

How can I detect a click event on an SVG element using JavaScript or jQuery?

Currently, I am developing a web application that utilizes SVG. However, I have encountered an issue: I am struggling to add a click event to each element within the SVG using jQuery. The problem arises when attempting to trigger the event; it seems like t ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

Toggle textboxes using jQuery depending on the radio button choice

I'm trying to make specific textboxes appear when a particular radio button is clicked on my form, but I want them to remain hidden otherwise. Here's an example of what I've implemented: HTML: Radio buttons: <p>Show textboxes<inpu ...

What is the process of converting code to JavaScript and React?

There are two methods defined as shown below. const handleClick = React.useMemo(() => !isRunning ? (items: string | string[]) => { if(Array.isArray(items)){ startRun({ items: items }); } else ...

Issue with IE preventing Selenium from triggering Onchange event and causing page to fail to Postback

I am currently working on a web application where selecting an item from one drop-down list triggers the loading of another. However, when using Selenium to automate this process, I have encountered an issue where the page post back is prevented and the se ...

Pattern to showcase quotes stylishly using regular expressions

I have text in my database that contains quotes. The raw form of these quotes looks like this: &gt;Some quote <br /> Some simple text<br /> <br> &gt; another quote with random <b>tags</b> and <a href=>links</a ...

Guide to updating the object value within an array in React

Is there a way to toggle the value of a specific object key called "clicked" to true using the spread operator in React? I want to be able to press a button and update the object's value. let questions = [ { title: "What do I want to learn ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

What is the best way to display form input fields depending on the selected value?

I've been struggling with a seemingly simple issue that I can't seem to find the right solution for, even after scouring Google. I have a form field for input and a select field with various values, including an "Other" option. Here's what ...

Pagination determined by the selections made in cascading dropdown menus

Does anyone know of a tutorial on implementing pagination that is specifically tailored to dependent drop lists? I've managed to display associated records based on a selection from a dropdown list with items like {Beavers, Cubs, Scouts, Venturers, Ro ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

What is the best way to initially hide a div using slide toggle and then reveal it upon clicking?

Is there a way to initially hide the div tag and then animate it in a slide toggle effect? I attempted using display:none on my '.accordion_box' followed by show() in slideToggle, but this results in adding the CSS property display: block. My goa ...

Is it possible for SqlCommand.ExecuteReader to automatically open the database connection?

Unusual behavior is happening on my website. I have a WCF Data service that provides JSON data to populate a jqGrid using javascript/ajax calls. In addition, there is server-side code that also accesses the same WCF service to retrieve data. Within my WC ...

The necessary directive controller is missing from the element in the current DOM structure

Can anyone explain the meaning of "required directive controller is not present on the current DOM element"? I encountered this error and would like some clarity. For reference, here is the link to the error: https://docs.angularjs.org/error/$compile/ctr ...

How to style large numbers with AngularJS

I'm facing a challenge with large numbers in a table and I'm seeking a solution to format them, ideally as $13b, $10m... Has anyone encountered this issue before and discovered a customized filter or solution for it? Appreciate any help! ...

Identify the invalid field within an Angular form

After the form is rendered, I need to identify which fields are not valid after 5 seconds. Currently, I have a button that is set as ng-disabled="!step1Form.$valid". However, I would like to add a CSS class, possibly in red, to highlight the invalid fields ...

Adjust the width of the Bootstrap 5 progress bar in Vue based on the progression of a countdown timer

I am looking to utilize a bootstrap 5 progress bar in order to display the remaining time of a countdown. I have set up the necessary markup within my vuejs component template. <div class="progress"> <div class="progress-bar&quo ...

Tips for incorporating Vue.js tag attributes in IDEA

I am using IDEA 2016.2.5 and I'm trying to incorporate Vue.js into my project. However, Vue has some tag attributes that IDEA is not recognizing and keeps highlighting as errors. I have installed the Vue Plugin and tried setting the HTML custom unkno ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...