java - Option pattern delimiter in regular expression -


i want create pattern match given string, , create several groups string.

the input string:

case 1: wp/video/video123/xyz/abc case 2: wp/video/video123 case 3: wp/video case 4: wp 

and desired output:

case1: group1=wp,group2=video,group3=video123 case2: group1=wp,group2=video,group3=video123 case3: group1=wp,group2=video case4: group1=wp 

the pattern have created matching first 2 cases, ignores last 2 cases:

(.*?)/+(.*?)/(.*?)[/.] 

you can want without regex using pure string.split , accessing groups:

string input ="wp/video/video123/xyz/abc"; string[] spts = input.split("/"); system.out.println("group1=" + spts[0] + ";group2=" + spts[1] + ";group3=" + spts[2]); 

this output group1=wp;group2=video;group3=video123 (see demo).

if need regex solution, nhahtdh provided sample regex uses optional non-capturing groups, suggest consuming characters .* @ end of pattern, or going further matches xyz/abc:

string str = "wp/video/video123/xyz/abc"; string rx = "([^/]+)(?:/([^/]+)(?:/([^/]+)?)?)?.*"; pattern ptrn = pattern.compile(rx); matcher m = ptrn.matcher(str); while (m.find()) {     system.out.println("group1=" + m.group(1) + ",group2=" + m.group(2) + ",group3=" + m.group(3)); } 

regex explanation:

  • ([^/]+) - 1st group of 1 or more characters other /
  • (?:/([^/]+)(?:/([^/]+)?)?)? - optional capturing group matches
    • / - literal /
    • ([^/]+) - 2nd group of 1 or more characters other /
    • (?:/([^/]+)?)? - optional capturing group matches same content described above
  • .* - match characters newline end of string not further matches. remove it if want further matches. or replace (?=\\s|$) look-ahead match before space or end of string.

see demo here


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

c# - Retrieve google contact -

javascript - How to insert selected radio button value into table cell -