gpt4 book ai didi

Java正则表达式分别匹配每个组

转载 作者:搜寻专家 更新时间:2023-10-31 19:55:09 24 4
gpt4 key购买 nike

我有这样一个字符串:

String text = "new SingleSizeProduct(422056, 1265858, 5430, '3XL', 75, 0, '14.90',     '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265859, 5341, 'L', 55, 0, '14.90',     '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265860, 5459, 'M', 45, 1, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265861, 5446, 'S', 35, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265862, 5458, 'XL', 60, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265863, 5511, 'XXL', 65, 0, '14.90', '16.50', '29.90', 'TL')";

和正则表达式:

String regex = "new SingleSizeProduct((.*))";

我想分别匹配所有 6 个组,但是当我匹配模式时,我得到这样的结果:

([0] => new SingleSizeProduct(422056, 1265858, 5430, '3XL', 75, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265859, 5341, 'L', 55, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265860, 5459, 'M', 45, 1, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265861, 5446, 'S', 35, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265862, 5458, 'XL', 60, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265863, 5511, 'XXL', 65, 0, '14.90', '16.50', '29.90', 'TL'),[1] => (422056, 1265858, 5430, '3XL', 75, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265859, 5341, 'L', 55, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265860, 5459, 'M', 45, 1, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265861, 5446, 'S', 35, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265862, 5458, 'XL', 60, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265863, 5511, 'XXL', 65, 0, '14.90', '16.50', '29.90', 'TL'),[2] => (422056, 1265858, 5430, '3XL', 75, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265859, 5341, 'L', 55, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265860, 5459, 'M', 45, 1, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265861, 5446, 'S', 35, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265862, 5458, 'XL', 60, 0, '14.90', '16.50', '29.90', 'TL'),new SingleSizeProduct(422056, 1265863, 5511, 'XXL', 65, 0, '14.90', '16.50', '29.90', 'TL'),)

如何分别匹配每个组?

最佳答案

.* 是贪婪的,所以它会尝试找到最大可能的匹配,这意味着 (.*) 将匹配

abc(foo)def(bar)ghi
^^^^^^^^^^^

如果你想让它找到最小可能的匹配

abc(foo)def(bar)ghi
^^^ ^^^

通过在 ? 之后添加 * 不情愿

String regex = "new SingleSizeProduct((.*?))";

您还需要转义 () 因为正如您所知,它们代表捕获组的开始和结束。

String regex = "new SingleSizeProduct\\((.*?)\\)";

顺便说一句。另一种解决方案是使用 .*? [^)]* 代替,这意味着,除 )

之外的所有内容
String regex = "new SingleSizeProduct(([^)]*))";

关于Java正则表达式分别匹配每个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com