Gurpreet Saini wrote:hello ,
Can you please explain me how regular expression is being used with given string in following code. Please explain bold code how is it working.
Thanks in advance.
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
\\s is a metacharacter that is used to search for white spaces
* is a greedy quantifier that means "zero or more"
Based on above your delimiter will be
a white_space that can occur zero or many times +fish+ again a white_space that can occur zero or many times
Based on your input , I put your delimiter between square brackets:
1[ fish ]2[ fish ]red[ fish ]blue[ fish]
If you run this piece of code the output is:
1
2
red
blue
Hope now things are clear.
Cheers,
Dragos