Reputation: 1892
I'm currently attempting to write some relatively simple(?) regex which captures a group of numbers which are then followed by specific characters.
https://regexr.com/4jp9h is a good example, I actually thought it was working but the 4 garlic cloves
example chucked a spanner in the works. I've played with not matching whitespace / the spaces but haven't had much luck at all.
All of the other matches are fine, eg: 900g, 900kg, so on and so forth. But I can't for the life of me figure out how to stop the 4 garlic cloves
example from matching.
Anyone got any ideas? :)
Upvotes: 0
Views: 70
Reputation: 57121
An alternative version is...
\d+[Kk]?[Gg]\s
This is allows Kg, KG, g, G, but also then tries to ensure that there is nothing following directly after it, so in your test set...
there 900G Match
900gvhello
hello garam masala
test g900gd
900kg Match
4 garlic cloves
So it doesn't match g900gd
or 4 garlic cloves
.
As pointed out, the \s
on the end may be better with alternatives which match different things.
The fourth bird suggests a non whitespace char (?!\S)
Or an alternative may also be a non word character [^w]
.
Upvotes: 2
Reputation: 5859
You could possibly just not allow any space between the digit and the characters that follow:
\d+[^ ]?[g-k]
Notice, that [g-k]
means that you accept a range of characters from g to k, i.e. examples like 900h
, 900ij
will match. If you do not want that and only want k
and g
characters to match, you can simply do:
\d+[^ ]?[gk]
If you are specifically interested in the kg
order, you can simply do:
\d+[^ ]k?g --> this is same as Code Maniac answer \d+k?g
Obviously also notice the ignore case flag i
- if you do not have that set, you will need to add upper-case letters to your regex as well.
Upvotes: 1
Reputation: 37755
\d+.?[g-k]
Why
4 g
matches ?
You have .?
which means match anything except new line once ( optional ), also i believe you want to match kg
or g
So you can simply use
\d+k?g
\d+
- Match one or more digitk?
- Match k
( optional )g
- Match g
Upvotes: 2