【问题标题】:Java regex can only use 1 quantifier in a lookback (need 2)Java 正则表达式在回溯中只能使用 1 个量词(需要 2 个)
【发布时间】:2019-08-16 17:32:58
【问题描述】:

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

我制作的正则表达式需要执行以下操作:
- 1d 测试 --> 删除 1d 并离开 'test'
- 测试 1d --> 移除 1d 并离开 'test'
- 1d test 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/过去它

感谢您帮助我!

【问题讨论】:

  • 你给一个空链接,按 CTRL+S 然后隐藏特定链接(确保它不仅仅是网站名称)
  • 您是否尝试过 replaceFirst..? string1.replaceFirst(Pattern.quote("1d"), "");
  • @NuthanKumar 这行得通,非常感谢。我没有想到这一点 :facepalm: (我确实使用了我自己的表达式而不是 Pattern.quote("1d"),因为它不仅适用于 1d
  • 那么,你想删除第一个&lt;1+ digits&gt;&lt;1+ letters&gt;吗?然后你需要str.replaceFirst("\\s*\\d+\\p{Alpha}+", "")。如果该单词必须是整个单词,请使用"\\s*\\b\\d+\\p{Alpha}+\\b"
  • @Banjer_HD,我会把它作为答案发布,请接受它

标签: java regex regex-lookarounds


【解决方案1】:

你试过用 replaceFirst() 吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多