I have a String that begins with a word and I want to make a substring which starts at index 0 and ends at the index of the next special character (space
, .
, !
, ?
, etc...). How would I go about doing that with a regex? Can I get the index of the first regex match? And how would the pattern look?
Thanks in advance!
You could use the following.
^\w+(?=\W)
Explanation:
^ # the beginning of the string
\w+ # word characters (a-z, A-Z, 0-9, _) (1 or more times)
(?= # look ahead to see if there is:
\W # non-word characters (all but a-z, A-Z, 0-9, _)
) # end of look-ahead
Example:
String s = "foobar!";
Pattern p = Pattern.compile("^\\w+(?=\\W)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println("Start:" + m.start() + " End:" + m.end());
System.out.println(m.group());
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments