简体   繁体   中英

Print a part of string that made a string match regex

I want to check if my String contains any letters(NSWE - map directions). And if it does I want to set direction = that letter and return either true or false.

Example:

input: 15.15.15 N

output I want to receive: N

output that direction = matcher.group(); gives me: 15.15.15 N

As expected it prints string that matched the regex. I want to print only the part that made it matched. Letter can be at beginning or at the end of the string. Any idea how to make it?

public boolean example (String value) {

    Pattern parrent = Pattern.compile(".*[a-zA-Z].*");
    Matcher matcher = parrent.matcher(value);        

    if(matcher.find()) {
        direction = matcher.group();
        System.out.println("direction" + direction);
        return false;
    }
    else
        return true;
    }

You don't have a group there!

Try this here instead:

Pattern pattern = Pattern.compile(".* (N|S|W|E)");

The point is: you basically have

non-whitespace whatever

a space

one of four letters which you are interested in.

Thus you want a simple pattern that ignores anything you don't care about; and groups around the element you want back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM