简体   繁体   中英

regular expression how to get substring?

This are my example data:

406/FG-2000

411/FA-2120

XX-226/2012-DFDF

OASDV-279/1016-FDFFD

how can with regex (only regex) in java i parse

406/FG-2000 -> 406 (from begining to /)

411/FA-2120 -> 411 (from begining to /)

XX-226/2012-DFDF -> 226 (from - to /)

OASDV-279/1016-FDFFD -> 279 (from - to /)

this are two rules. (from begining to /) or (from - to /)

This code does what you asked for:

input.replaceAll(".*(^|-)(.*?)/.*", "$2")

If you want to restrict it to digits only, change the matching regex to ".*(^|-)(\\d*?)/.*"

Here's a test:

public static void main(String[] args) {
    String[] inputs = { "406/FG-2000", "411/FA-2120", "XX-226/2012-DFDF", "OASDV-279/1016-FDFFD" };
    for (String input : inputs)
        System.out.println(input.replaceAll(".*(^|-)(.*?)/.*", "$2"));
}

Output:

406
411
226
279

Try this one:

(^|-)[0-9]+/

It will match any numbers from the beginning or from a - to the /

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