Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern numbers followed by a character

Tags:

c#

regex

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?

like image 740
Naveen Avatar asked May 28 '12 14:05

Naveen


People also ask

What does '$' mean in regex?

$ 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 sequence in regex?

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 “(” .

What is difference [] and () in regex?

[] 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 .


1 Answers

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).

like image 73
SimpleVar Avatar answered Oct 16 '22 03:10

SimpleVar