我有一种情况
CF-123/NAME-ANUBHAV/RT-INR 450/SI-No smoking/SC-123
Regex应该与Java兼容,并且需要在一条语句中完成。 其中,我必须从此字符串中选择一些信息。这些信息以预定义标签作为前缀,并且必须将其放在命名组中。
(CF-) confirmationNumber = 123
(Name-) name = ANUBHAV
(RT-) rate = INR 450
(SI-) specialInformation = No smoking
(SC-) serviceCode = 123
I have written below regex:
^(CF-(?<confirmationNumber>.*?)(\/|$))?(([^\s]+)(\/|$))?(NAME-(?<name>.*?)(\/|$))?([^\s]+(\/|$))?(RT-(?<rate>.*?)(\/|$))?([^\s]+(\/|$))?(SI-(?<specialInformation>.*?)(\/|$))?([^\s]+(\/|$))?(SC-(?<serviceCode>.*)(\/|$))?
There can be certain scenarios.
**1st:** CF-123/**Ignore**/NAME-ANUBHAV/RT-INR 450/SI-No smoking/SC-123
**2nd:** CF-123//NAME-ANUBHAV/RT-INR 450/SI-No smoking/SC-123
**3rd:** CF-123/NAME-ANUBHAV/RT-INR 450/**Ignore**/SI-No smoking/SC-123
在用/分隔的字符串之间可能有某些标签,我们不需要在命名组中捕获它们。enter code here
基本上,我们需要选择CF-,NAME-,RT-,SI-,SC-,并必须在confirmationNumber,name,rate,specialInformation ,serviceCode。不需要捕获字符串之间的任何内容。
要找到您感兴趣的五位信息,您可以将模式与命名组一起使用,并使用正则表达式模式进行编译
然后,您可以使用正则表达式匹配器查找组
String line = "CF-123/**Ignore**/NAME-ANUBHAV/RT-INR 450/SI-No smoking/SC-123";
String pattern = "CF-(?<confirmationNumber>[^/]+).*NAME-(?<name>[^/]+).*RT-(?<rate>[^/]+).*SI-(?<specialInformation>[^/]+).*SC-(?<serviceCode>[^/]+).*";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
之后,您可以使用匹配的组:
if (m.find( )) {
String confirmationNumber = m.group("confirmationNumber");
String name = m.group("name");
String rate = m.group("rate");
String specialInformation = m.group("specialInformation");
String serviceCode = m.group("serviceCode");
// continue with your processing
} else {
System.out.println("NO MATCH");
}