index of a regex in a String

G

Guest

How can I implement this?
(Without checking characters one-by-one with my code)

String a = " abc";
int b = a.indexOfRegex("\s", 0);
// b is 2 (index of first non-whitespace character)
 
J

John McGrath

How can I implement this?
(Without checking characters one-by-one with my code)

String a = " abc";
int b = a.indexOfRegex("\s", 0);
// b is 2 (index of first non-whitespace character)

Note that you need to escape the backslash: "\\s", not "\s".

Pattern pattern = Pattern.compile( "\\s" );
Matcher matcher = pattern.matcher( a );
if ( matcher.find() ) {
int start = matcher.start();
} else {
// not found
}
 
A

Alan Moore

Note that you need to escape the backslash: "\\s", not "\s".

Pattern pattern = Pattern.compile( "\\s" );
Matcher matcher = pattern.matcher( a );
if ( matcher.find() ) {
int start = matcher.start();
} else {
// not found
}

That will return the index of the first *whitespace* character, zero.
If you want the index of the first non-whitespace character, either
change the regex to "\\S" or use matcher.end().
 
J

John McGrath

That will return the index of the first whitespace character, zero.
If you want the index of the first non-whitespace character, either
change the regex to "\\S" or use matcher.end().

Yes, that is true. I think the OP was looking for how to find the
location that an arbitrary pattern matches - which is what the code I
posted does. I was not paying attention to the actual pattern he provided.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top