indexOf and regular expression, is it possible?
indexOf and regular expression, is it possible?
How?
Thanks!
// IndexOf_regex.java
public class IndexOf_regex
{
public static void main ( String[] args ) {
String languages = "English French Portuguese Spanish ";
if ( languages.indexOf("\\S") != -1 )
{
languages = languages.substring(0,languages.length()-1);
}
else {languages = "probably heshe speaks English.";}
System.out.println("languages = " + languages);
} // main END
} // IndexOf_regex.java END
/*
Result:
languages = probably heshe speaks English.
*/
DrLaszloJamf, tschodt , thanks for the lesson, DrLaszloJamf and for the hint, tschodt.
It worked:
// IndexOf_regex.java
import java.util.regex.*;
public class IndexOf_regex
{
public static void main ( String[] args ) {
String languages = "English French Portuguese Spanish ";
Pattern p = Pattern.compile("\\S{3}");
Matcher m = p.matcher(languages);
if (m.find()) {
languages = languages.substring(0,languages.length()-1);
} // fim do m.find
else {languages = "probably heshe speaks English.";}
System.out.println("languages = " + languages);
} // main END
} // IndexOf_regex.java END
/*
Result:
languages = English French Portuguese Spanish
*/
If you just want to ensure that there non-whitespace characters in the string, do this if ( !languages.matches("\\s*") )
But I don't understand what you're trying to inside the if block: languages = languages.substring(0,languages.length()-1);
All that does is chop off the last character.
Oh, I get it: there's a space at the end you want to get rid of. You could just do this: languages = languages.replaceFirst("\\s+$", "");
In future, please put sample code inside [code][/code] tags; that makes it a lot easier to read.
uncle_alice,
Thanks for the hints:
1. Oh, I get it: there's a space at the end you want to get rid of. You could just do this: languages = languages.replaceFirst("\\s+$", "");
2. In future, please put sample code inside code tags; that makes it a lot easier to read.
3. If you just want to ensure that there are non-whitespace characters in the string, do this
if ( !languages.matches("\\s*") )
Oh, yes, yes, yes, yes! xiarcel, I believe that is the Final Solution, string.trim();, thanks!