ihsany
ihsany

Reputation: 1050

RegEx to match a number in the second line

I need a regex to match a number in the second line. Similar input is like this:

^C1.1
xC20 
SS3 
M 4 

Decimal pattern (-?\d+(\.\d+)?) matches all numbers and second number can be get in a loop on the code behind but I need a regular expression to get directly the number in the second line.

Upvotes: 4

Views: 2531

Answers (4)

inhan
inhan

Reputation: 7470

I would probably use the captured group in /^.*?\r?\n.*?(-?\d+(?:\.\d+)?)/ where…

^                  # beginning of string
.*?                # anything...
\r?\n              # followed by a new line
.*?                # anything...
(                  # followed by...
   -?              # an optional negative sign (minus)
   \d+             # a number
   (?:             #   -this part not captured explicitly-
       \.\d+       # a dot and a number
   )?              #   -and is optional-
)

If it is a flavor that supports lookbehind then there are other alternatives.

Upvotes: 0

FrankieTheKneeMan
FrankieTheKneeMan

Reputation: 6800

/^[^\r\n]*\r?\n\D*?(-?\d+(\.\d+)?)/

This operates by capturing a single line at the beginning of the input:

^         Beginning of the string
[^\r\n]*  Anything that isn't a line terminator
\r?\n     A newline, optionally preceded by a carriage return

Then all the non digit characters, then your numbers.

Since you've now repeatedly changed your needs, try this on for size:

/(?<=\n\D*)-?\d+(\.\d+)?/

Upvotes: 2

Martin Milan
Martin Milan

Reputation: 6390

Check out group 1 of anything that this matches:

^.*?\r\n.*?(\d+)

If that doesn't work, try this:

^.*?\r\n.*?(\d+)

Both are with multiline NOT set...

Upvotes: 0

raddevon
raddevon

Reputation: 3340

I was able to capture it with this regex.

.*\n\D*(\d*).*\n

Upvotes: 1

Related Questions