[solved]Finding any alpha numeric within a string.

Discussion in 'Plugin Development' started by TopGear93, Apr 26, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    TopGear93

    My question is how do i find any letter or number within a string? Im trying to find a way to track anything that appears next to a "@"

    if(event.getMessage().startsWith("@")){

    instead of making a line for every letter and number how do i simply find them all within 1 line?
     
  2. Offline

    desht

    I would strongly recommend regular expressions to do this neatly.

    PHP:
    Pattern pat Pattern.compile("^@\\w");
    Matcher m pat.matcher(event.getMessage());
    if (
    m.matches()) {
      
    // ...
    }
    "^@\\w" means start at beginning of line ("^), then look for a literal "@", followed by any alphanumeric ("\\w"). Note the double backslash - that's because of Java's string quoting & escaping rules.

    There's also String.matches(regex) which does basically the same thing, more concisely but not as flexible.

    If you want to know just what alphanumeric follows the "@", it's only slightly more complex:
    PHP:
    Pattern pat Pattern.compile("^@(\\w)");    // note the parentheses now
    Matcher m pat.matcher(event.getMessage());
    if (
    m.find()) {
      
    String matched m.group();
      
    // ...
    }
    This guide is useful: http://www.regular-expressions.info/java.html, along with http://docs.oracle.com/javase/tutorial/essential/regex/.
     
    TopGear93 likes this.
  3. Offline

    TopGear93

    thanks, ive been trying to figure out what those expressions meant for awhile now.
     
Thread Status:
Not open for further replies.

Share This Page