简体   繁体   English

Java-使用正则表达式捕获可选字段?

[英]Java - Capture optional field with regexp?

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? 如您所见,有一个名为RenkGidis的可选字段,如果它不为null,如何从RenkGidis获取值?

with the regex code that i wrote above, i can get if RenkGidis exists in group(4) like 12:00; 使用我上面编写的正则表达式代码,我可以得出RenkGidis是否存在于group(4)中,例如12:00; RenkGidis=0000FF but group(4) must be only 12:00 . RenkGidis = 0000FF,但group(4)必须仅为12:00

I hope that I could explain my problem. 我希望我能解释我的问题。

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: 作为Java字符串:

"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 ; ) [^;\\s]*[;\\s] ->任何非空格或;字符的取反)


As Alan mentioned in the comments, for not getting a null match for the optional part, eg just make RenkGidis optional and wrap the value in an alternation with nothing: ([^;\\s]*;|) 正如艾伦(Alan)在评论中提到的那样,由于未获得可选部分的null匹配,例如,使RenkGidis成为可选部分,然后将值包装成一个没有其他内容的交替形式: ([^;\\s]*;|)

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

As a Java string: 作为Java字符串:

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

The regex could look like this 正则表达式可能看起来像这样

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

Group 5 will then be either " RenkGidis=0000FF;" 然后,第5组将为“ RenkGidis = 0000FF;”。 or " ". 要么 ” ”。 You can then use a second regex to get 0000FF. 然后,您可以使用第二个正则表达式获得0000FF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM