0

I've a regex that correctly captures values from the result of a string.

regex is look like;

intGetHatSaatRenk_v22=anyType{SiraNo=(.*?); HatKodu=(.*?) ; GunTipi=(.*?); Gidis=(.*?); ? }; 

But the problem is the source is like;

intGetHatSaatRenk_v22=anyType{SiraNo=54; HatKodu=502 ; GunTipi=C; Gidis=12:00; RenkGidis=0000FF; }; 

intGetHatSaatRenk_v22=anyType{SiraNo=55; HatKodu=502 ; GunTipi=C; Gidis=12:07; }; intGetHatSaatRenk_v22=anyType{SiraNo=56; HatKodu=502 ; GunTipi=C; Gidis=12:14; };

as you can see there is an optional field that named RenkGidis, how can i get the value from RenkGidis if it's not null?

with the regex code that i wrote above, i can get if RenkGidis exists in group(4) like 12:00; RenkGidis=0000FF but group(4) must be only 12:00.

I hope that I could explain my problem.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Swisyn
  • 397
  • 1
  • 6
  • 11

2 Answers2

1

Might want to make the last group optional:

intGetHatSaatRenk_v22=anyType\{SiraNo=([^;\s]*);\s+HatKodu=([^;\s]*)\s*;\s+GunTipi=([^;\s]*);\s+Gidis=([^;\s]*);(?:\s+RenkGidis=([^;\s]*);)?

As a Java string:

"intGetHatSaatRenk_v22=anyType\\{SiraNo=([^;\\s]*);\\s+HatKodu=([^;\\s]*)\\s*;\\s+GunTipi=([^;\\s]*);\\s+Gidis=([^;\\s]*);(?:\\s+RenkGidis=([^;\\s]*);)?"

At the last group ( ?: prevents the group to be captured into output. ( inside ) catpured as usual.

Also changed .*? to [^;\s]* (negation of [;\s] -> any characters, that are no white-space or ;)


As Alan mentioned in the comments, for not getting a null match for the optional part, e.g. just make RenkGidis optional and wrap the value in an alternation with nothing: ([^;\s]*;|)

intGetHatSaatRenk_v22=anyType\{SiraNo=([^;\s]*);\s+HatKodu=([^;\s]*)\s*;\s+GunTipi=([^;\s]*);\s+Gidis=([^;\s]*);(?:\s+RenkGidis=)?([^;\s]*|)

As a Java string:

"intGetHatSaatRenk_v22=anyType\\{SiraNo=([^;\\s]*);\\s+HatKodu=([^;\\s]*)\\s*;\\s+GunTipi=([^;\\s]*);\\s+Gidis=([^;\\s]*);(?:\\s+RenkGidis=)?([^;\\s]*|)"
Community
  • 1
  • 1
Jonny 5
  • 12,171
  • 2
  • 25
  • 42
0

The regex could look like this

intGetHatSaatRenk_v22=anyType\{SiraNo=(.*?); HatKodu=(.*?) ; GunTipi=(.*?); Gidis=(.*?);( RenkGidis=.*?;\s*|\s*)\};

Group 5 will then be either " RenkGidis=0000FF;" or " ". You can then use a second regex to get 0000FF.

Tesseract
  • 8,049
  • 2
  • 20
  • 37