• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Regular expression

 
Ranch Hand
Posts: 295
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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());
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic