简体   繁体   中英

How to pattern match first occurence?

How can I always take the first element matched by a pattern?

Pattern pattern = Pattern.compile("(\\d+)K");
Matcher matcher = pattern.matcher("CARRY8K");
baggageWeight = matcher.group(); //I'd like to extract the "8"

Result: java.lang.IllegalStateException: No match found

Why?

matcher.group() throws IllegalStateException If no match has yet been attempted, or if the previous match operation failed. Here you haven't used find() which attempts to find the next subsequence of the input sequence that matches the pattern.

If you do like this you extract "8" from the String "CARRY8K"

Pattern pattern = Pattern.compile("(\\d+)K");
Matcher matcher = pattern.matcher("CARRY8K");
if (matcher.find()) {
   System.out.println(matcher.group(1));
}

I would suggest using String.indexOf(string) to find the location of the string within the main string. Using indexOf you can then extract the value at the specified index. For example:

String s = "CARRY8K";
int index = s.indexOf("8");

"index" will be set to the location of the first instance of the specified character. In this case, "8". You can then use the index to perform other operations--either to print the location of the character, or remove it from your main string.

If you want to remove it, just use a stringbuilder and the setCharAt() method:

StringBuilder newString = new StringBuilder(s);
newString.setCharAt(index, '');

This will replace the character at the specified index to a blank, effectively removing it from the main string.

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