正则表达式,选择在点号之间且不包含括号的分组。

huangapple go评论146阅读模式
英文:

Regex to select groups between dots without brackets

问题

以下是您要翻译的部分:

  1. 我有这样的字符串:
  2. test.as123[13].tdfv
  3. Parent.child1
  4. test.d12[0].asdf
  5. 我需要一个正则表达式,可以给我匹配到这样的组:
  6. - test, as123, tdfv
  7. - Parent, child1
  8. - test, d12, asdf
  9. 所以我需要在句点处分割这些组,并删除名称中的括号。
  10. 我尝试使用否定字符类,就像这样:
  11. ([^\W\d]+)
  12. 但结果会是"child"而不是"child1"
  13. 我的问题是,我不确定如何忽略特定的字符串`\[\d\]`并继续匹配`\d`
  14. 我尝试使用负向先行断言,但我觉得我做错了什么。
  15. 这是我的尝试:
  16. \w+(?!\[[0-9]*?\])
  17. 这确实匹配了,例如:
  18. - test, 13, tdfv

请注意,我已经删除了不需要的部分,只返回了翻译好的内容。如果您有任何其他问题,请随时提出。

英文:

I got Strings like this:

  1. test.as123[13].tdfv
  2. Parent.child1
  3. test.d12[0].asdf

I need a regex which gets me groups like this:

  • test, as123, tdfv
  • Parent, child1
  • test, d12, asdf

So I need to divide the groups on the dot and also remove the brackets in its name.

I tried using negation like this:

  1. ([^\W\d]+)

But there will be child as result and not child1.

My problem is that I'm not sure on how to ignore the specific String \[\d\] and keep on matching \d

I tried using negative lookahead, but I think I'm doing something wrong.
Here's my attemp:

  1. \w+(?!\[[0-9]*?\])

This does match for example:

  • test, 13, tdfv

答案1

得分: 3

  1. // You can remove all occurrences of digits inside square brackets and then split on a dot:
  2. .replaceAll("\\[\\d+]", "").split("\\.")
  3. // Or, you may directly split on the `(?:\\[\\d+])?\\.` pattern:
  4. .split("(?:\\[\\d+])?\\.")
  5. // It matches
  6. // - `(?:\\[\\d+])?` - an optional occurrence of a `[`, 1+ digits, `]`
  7. // - `\\.` - a dot.
  8. // See the [Java demo online][1]:
  9. String s = "test.as123[13].tdfv";
  10. String results[] = s.replaceAll("\\[\\d+]", "").split("\\.");
  11. System.out.println(Arrays.toString(results));
  12. // => [test, as123, tdfv]
  13. String results2[] = s.split("(?:\\[\\d+])?\\.");
  14. System.out.println(Arrays.toString(results2));
  15. // => [test, as123, tdfv]
英文:

You can remove all occurrences of digits inside square brackets and then split on a dot:

  1. .replaceAll("\\[\\d+]", "").split("\\.")

Or, you may directly split on the (?:\[\d+])?\. pattern:

  1. .split("(?:\\[\\d+])?\\.")

It matches

  • (?:\[\d+])? - an optional occurrence of a [, 1+ digits, ]
  • \. - a dot.

See the Java demo online:

  1. String s = "test.as123[13].tdfv";
  2. String results[] = s.replaceAll("\\[\\d+]", "").split("\\.");
  3. System.out.println(Arrays.toString(results));
  4. // => [test, as123, tdfv]
  5. String results2[] = s.split("(?:\\[\\d+])?\\.");
  6. System.out.println(Arrays.toString(results2));
  7. // => [test, as123, tdfv]

huangapple
  • 本文由 发表于 2020年8月27日 17:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63613019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定