简体   繁体   中英

Java Regex Alphabet Followed By Number

I am getting file names as string as follows:

file_g001  
file_g222  
g_file_z999

I would like to return files that contains "g_x" where x is any number (as string). Note that the last file should not appear as the g_ is followed by an alphabet and not a number like the first 2.

I tried: file.contains("_g[0-9]*$") but this didn't work.

Expected results:

file_g001  
file_g222

Are you using the method contains of String ? If so, it does not work with regular expression.

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contains-java.lang.CharSequence-

public boolean contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values.

Consider using the method matches .

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)

Your regular expression is also fine, we'd just slightly improve that to:

^.*_g[0-9]+$

or

^.*_g\d+$

and it would likely work.


The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.


Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^.*_g[0-9]+$";
final String string = "file_g001\n"
     + "file_g222\n"
     + "file_some_other_words_g222\n"
     + "file_g\n"
     + "g_file_z999";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

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