Java 正则表达式只能在回顾中使用 1 个量词(需要 2 个)

Java regex can only use 1 quantifier in a lookback (need 2)

我不能在回顾中使用超过 1 个量词。

我制作的正则表达式需要做以下事情:
- 1d 测试 --> 删除 1d 并留下 'test'
- 测试 1d --> 删除 1d 并留下 'test'
- 1d 测试 1d --> 删除第一个 1d 并留下 'test 1d'

我想要的正则表达式不起作用:

String string = "11d test 1d";

String[] parts = 
          string.split("(^\d+[a-zA-Z]\s)|(\s\d+[a-zA-Z]$(?<!^\d+[a-zA-Z]\s.*))");

输出:

test

有效的正则表达式(但仅适用于固定长度的字符串,计算点数):

String string = "11d test 1d";

String[] parts = 
         string.split("(^\d+[a-zA-Z]\s)|(\s\d+[a-zA-Z]$(?<!^\d+[a-zA-Z]\s.......))");

输出:

test 1d

两个量词(在回顾中)是+(在\d之后)和*(在\s之后)

如果你想自己测试一下,可以在https://regex101.com/

中通过它

谢谢你帮我!

你试过 replaceFirst() 了吗?

string1.replaceFirst("(^\d+[a-zA-Z]\s)|(\s\d+[a-zA-Z]$)", "");