1

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 /)

1
  • 1
    According to your testdata: is a third rule "must be digits"? Commented Apr 11, 2012 at 6:40

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

i tested here: roblocher.com/technotes/regexp.aspx but i get group 1 and group 2 as result. Why not just 1 result?
groups are bracketed expressions. there are two groups in the regex, but the first one is there only because of the "OR" expression. the second group is the "real" capturing group
0

Try this one:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.