Z
Z
Zaur Abdulgalimov2016-05-04 23:37:12
Java
Zaur Abdulgalimov, 2016-05-04 23:37:12

How to properly format a regular expression in Java?

There is a line like "ping pong 123".
There is a regular expression:

Pattern p = Pattern.compile("ping\s*(pong\s*)?(?<SimpleText>.+)?");

Is it possible to somehow indicate to Java that if there is a word "pong" - then it should be in the first group, and not in the SimpleText group?
Those. I want to get results like this:
Matcher m = p.matcher("ping pong 123");
System.out.println(m.group("SimpleText")); // ожидается 123

Matcher m = p.matcher("ping 123");
System.out.println(m.group("SimpleText")); // ожидается 123

Matcher m = p.matcher("ping pong");
System.out.println(m.group("SimpleText")); // ожидается null;  по факту: "pong"

Those. I want the result to be null in the last example, not "pong".

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question