Home > Mobile >  Regex get the string value in between \n's in various situations
Regex get the string value in between \n's in various situations

Time:12-31

I'm trying to extract the Test Data1's value

Currently have..

(?<=(?i)Test Data1)(.*)[^|\n] 
(?<=(?i)Test Data1)[)?]*[^\n] 
(?<=(?i)Test Data1)[\s:?](.*)[^\n] 

Case #1. \nTest Data1: {1, 2, 3}\nTest Data2: {4, 5, 6}\n

Case #2. \nTest Data1 {1, 2, 3}\nTest Data2 {4, 5, 6}\n

Case #3. \nTest Data1:\n{1, 2, 3}\nTest Data2: {4, 5, 6}\n

Case #4. \nTest Data1\n{1, 2, 3}\nTest Data2 {4, 5, 6}\n

Current regex I have returns case #1 and #2 fine, but since case#3 and case#4 have an extra \n before {1, 2, 3}, my regex just fails.

Is there a better/improved regex that I can always only get the Test Data1's value {1, 2, 3} in those 4 situations above?

CodePudding user response:

In case #4 you have

(?<=(?i)Test Data1)[\s:?](.*)[^\n] 

Is your intent that there be an optional whitespace or colon after Test Data1? That would be

[\s:]?

but you have

[\s:?]

which means "whitespace or colon or a question mark", and it's not optional.

CodePudding user response:

Is this the result you wanted

Test Data1:?\n?\s?(\{\d ,\s \d ,\s \d \})

CodePudding user response:

You can use

(?i)Test Data1[\s:]*\K.*

See the regex demo. Details:

  • (?i) - case insensitive matching ON
  • Test Data1 - a literal text
  • [\s:]* - zero or more whitespaces and : chars
  • \K - omit all text matched so far
  • .* - match the current line till end (. matches any char but line break chars)

Depending on regex flavor, you can also use

(?i)Test Data1[\s:]*\K.*
(?i)(?<=Test Data1[\s:]*).*
(?i)Test Data1[\s:]*(.*)
  • Related