0

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? :)

2
  • You want to match d900g or 900gd also ? can you list out what will be desired result for such cases ? Commented Aug 24, 2019 at 17:31
  • Please, edit your question and add your test cases with expected result. Commented Aug 24, 2019 at 17:53

3 Answers 3

2
\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 digit
  • k? - Match k ( optional )
  • g - Match g
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

@Thefourthbird, I wasn't sure of the best way - it may be that or just not a word character ( I tried [^\w]). Have to see what OP thinks.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.