I am trying get the Regex right for the following scenario but have some trouble. Below is the scenario.
My string looks like this:
"The office timing (h) is from 8h to 18h."
From the above string I need "8h"
and "18h"
.
So far I have done this "[0-9]*[h]"
. But this gives me "h"
, "8h"
and "18h"
.
Any ideas from experts out there?
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
How do you match a character sequence in regex? To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches “.” ; regex \+ matches “+” ; and regex \( matches “(” .
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
Replace [0-9]*[h]
with [0-9]+h
The +
means it must appear once or more. And there is no use in bracketing the h
, because it stands alone.
You can also use \d+h
for more readability (\d
matches any digit).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With