Alex
Alex

Reputation: 120

Java Regular Expression match one or more characters in list

I have some strings:

And I want to separate 19 with ("x" or "." one or more times) and 100. I tried to use regex:

 (x|\.)+

to group but it can not match all case above. Which regex can match all case above?

Upvotes: 2

Views: 5027

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You may use

(\d+)(\s*[x.][x.\s]*)(\d+)

See the regex demo

Details

  • (\d+) - Group 1: one or more digits
  • (\s*[x.][x.\s]*) - Group 2:
    • \s* - 0+ whitespaces
    • [x.] - an x or .
    • [x.\s]* - 0+ chars that are either x, . or whitespace chars
  • (\d+) - Group 3: one or more digits

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163362

For your example, you could capture what is before 100 and 100 in 2 capturing groups:

(\d+[x. ]+)(\d+)

Explanation

  • Capturing group (group 1) (
  • Match one or more digits \d+
  • Match one or more times x, . or whitespace [x. ]+ using a character class
  • Close capturing group )
  • Capture in a group (group 2) one or more digits (\d+)

Upvotes: 1

sobczak.dev
sobczak.dev

Reputation: 1308

You can use regex:

public static Matcher split(String text) {
    Pattern pattern = Pattern.compile("(\\d+)(x*)(\\s*)(\\.*)(\\d+)");
    Matcher matcher = pattern.matcher(text);
    matcher.find();

    return matcher;
}

This regex works for test data:

19xx.100
19x.100
19..100
19x .100

After then matcher.group(1) will return 19 and matcher.group(5) will return 100

Upvotes: 1

Related Questions