java - How can I make a group optional which capturing a pattern and also capture the same group number? -
pattern pattern = pattern.compile("\\d{4}\\s+[a-z|a-z]{2}\\s+plain\\stext\\s+(.*?)\\(ns\\)"); matcher matcher = pattern.matcher("2007 al plain text ap2345 (ns)"); while (matcher.find()) { system.out.println(matcher.group(1)); } i want work input1 = 2007 al plain text ap2345 (ns) (the above regex work this) fails input2 = "ap2345". want capture both these strings in same group number means need make previous captures optional. how can that?
edit::: want same group number work both when strings value 2007 al plain text ap2345 (ns) or ap2345
i not sure if understood problem correctly before explain check regex
(\\d{4}\\s+[a-za-z]{2}\\s+plain\\stext\\s+)?(\\w+)(\\s+\\(ns\\))? like
pattern pattern = pattern .compile("(\\d{4}\\s+[a-za-z]{2}\\s+plain\\stext\\s+)?(\\w+)(\\s+\\(ns\\))?"); matcher matcher = pattern.matcher("2007 al plain text ap2345 (ns)"); while (matcher.find()) { system.out.println(matcher.group(2)); } example1 2007 al plain text ap2345 (ns) output -> ap2345
example2 ap2345 output -> ap2345
this regex try store optional part 2007 al plain text in group 1. if string wont contain part group 1 contain null. ok since interested in part after stored in group 2. assumed group 2 contain 1 word why used \\w+ (\\w match letter, digit, , _). if want accept more words try using (.+?)(\\s+\\(ns\\)|$) instead.
Comments
Post a Comment