andys
andys

Reputation: 708

Regex: match pattern after some pattern

I have strings:

Word AB70 60.1 Another
Word AB70 60 Another
Word AB70 D65.1 Another
Word AB70(-20) D65.1 Another
Word AB-70 D65.1 Another

I need to get 60.1 or 60 or 65.1 without D letter (letter could be any)

My thoughts was on regex

AB-?\d+(?:\(-?\d+\))?\K\d+(?:\.\d+)

What I was thinking is to find AB70, forget it and get next match with \d+(?:\.\d+)

but it is not working... what I am doing wrong?

Upvotes: 0

Views: 3171

Answers (2)

Luke
Luke

Reputation: 156

(?:) represents a non-capturing group in regex, so you wouldn't get the next match with \d+(?:\.\d+)

Assuming the pattern you are matching always starts with AB, the regex below should work. It looks for AB, followed by any amount of non-white space, non-digit characters. The capture group captures 0 or more digit characters, optionally with a decimal point, followed by 0 or more digits.

AB\S*\D*(\d*\.?\d*)

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You did not take into account the spaces and letter:

AB-?\d+(?:\(-?\d+\))?\s*[A-Za-z]*\K\d+(?:\.\d+)?

See the regex demo

Details

  • AB - an AB char sequence
  • -?\d+(?:\(-?\d+\))? - an optional -, 1+ digits and then an optional sequence of (, an optional -, 1+ digits and ) char
  • \s* - 0+ whitespaces
  • [A-Za-z]* - 0 or more letters
  • \K - match reset operator
  • \d+ - 1+ digits
  • (?:\.\d+)? - an optional sequence of . and 1+ digits after.

Upvotes: 1

Related Questions