Domanda

Ho la seguente stringa

52x10x20x30x40
.

La stringa può essere estesa ma con lo stesso schema e ci saranno altre stringhe su entrambi i lati: ad esempio

"Hello something 52x10x20x30x40 bla bla bla"
.

Voglio catturare tutte le 2 cifre.

Ho il seguente regex

Pattern.compile("(\\d\\d)([x]\\d\\d)+");
.

Ma con questo regex ottengo solo i seguenti gruppi:

1: 52
2: x40
.

È stato utile?

Soluzione

Why not simply:

"52x10x20x30x40".split("x");

?

Forgot to mention that there can be other strings on both sides.

You could search for "\\d{2}(x\\d{2})+", and use split("x") on the match.

Altri suggerimenti

Regex doesn't support variable group lengths.

Use a split method instead, e.g. Guava's Splitter:

Iterable<String> tokens = Splitter.on('x').split(str);

If you just want to capture all two digit numbers you could use this expression:

(?<!\d)(\d\d)(?!\d)

Usually you can only get the last substring that a repeated capturing group matches. (.NET regex differs in this regard.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top