This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Five Lines of Code and have Christian Clausen on-line!
See this thread for details.
Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Regular expression

 
Ranch Hand
Posts: 295
  • Mark post as helpful
  • send pies
  • 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
  • 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

 
It's a beautiful day in this neighborhood - Fred Rogers. Tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic