❮ Previous Next ❯

Java regular expression Quantifiers

We can use Java regular expression quantifiers to specify number of occurrences to match.

We can use quantifiers to specify number of occurrences to match.
a: exactly one a
a+: at least one a
a*: any number of a including zero number also
a?: at most one a

let's see a demo program by using quantifiers:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExDemo3
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("abaabaaab");
while(m.find())
{
System.out.println(m.start()+"..."+m.group());
}
}
}
Output
X=a X=a+ X=a+ X=a*

0...a

2...a

3...a

5...a

6...a

7...a

0...a

2...aa

5...aaa

0...a

1...

2...a

3...a

4...

5...a

6...a

7...a

8...

9...

0...a

1...

2...aa

4...

5...aaa

8...

9...

Pattern class split():

We can use Pattern class split() method to split the given target string according to the given pattern.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExDemo4
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("\\s");
String[] s=p.split("Silan Technology Services"); for(String s1:s)
{
System.out.println(s1);
}
}
}
Output
Silan
Technology
Services

String class split()

String class also contains split() method to split given target string according to particular pattern.

Example

String s="Silan Software";
String[] s1=s.split("Silan Software");
for(String s2:s1)
{
System.out.println(s2);
}
Output
Silan
Software

NOTE: The Pattern class split can take target string as an argument where as String class split() can take regular expression as an argument.

❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-N6/530,2ND Floor
Nayapalli,Jayadev Vihar
      Bhubaneswar-751015
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved