Regex to get the first number after a specific line, followed by any data, up to the number

I have some of the data extracted from the database and contain the information I need. The text is entered in free form, so it is written in different ways. The only thing I know for sure is that I'm looking for the first number after a given line, but after that a certain line (before the number) can also be any text.

I tried this (where mytokenis the line that I know for sure there), but it does not work.

/(mytoken|MYTOKEN)(.*)\d{1}/
/(mytoken|MYTOKEN)[a-zA-Z]+\d{1}/
/(mytoken|MYTOKEN)(.*)[0-9]/
/(mytoken|MYTOKEN)[a-zA-Z]+[0-9]/

It mytokencan even be written in capitals, in lower case or in a combination of capitals and in lower case. Can an expression be case insensitive?

+4
source share
3 answers

You don't need a lazy match, since you want to match any number of characters without digits to the first digit . It is better to do this with \D*:

/(mytoken)(\D*)(\d+)/i

Watch the regex demo

Template Details:

  • (mytoken)- correspondence of group 1 mytoken(case insensitive, since a modifier exists /i)
  • (\D*) - Group 2, corresponding to zero or several characters other than a digit
  • (\d+) - Group 3 corresponds to 1 or more digits.

Note that it \Dalso matches .newlines , you need a DOTALL modifier to match between newlines.

+3
source

. , : .*?. , \d.

Regex: /(mytoken|MYTOKEN)(.*?)\d/

- Regex

+2

You can use the opposite:

/(mytoken|MYTOKEN)(\D+)(\d)/

This says: mytoken followed by not a number , followed by a number. A (lazy) point-star-soup is not always the best choice. In this example, the desired number will be $3.

+2
source

All Articles