英文:
Regex to select groups between dots without brackets
问题
以下是您要翻译的部分:
我有这样的字符串:
test.as123[13].tdfv
Parent.child1
test.d12[0].asdf
我需要一个正则表达式,可以给我匹配到这样的组:
- test, as123, tdfv
- Parent, child1
- test, d12, asdf
所以我需要在句点处分割这些组,并删除名称中的括号。
我尝试使用否定字符类,就像这样:
([^\W\d]+)
但结果会是"child"而不是"child1"。
我的问题是,我不确定如何忽略特定的字符串`\[\d\]`并继续匹配`\d`。
我尝试使用负向先行断言,但我觉得我做错了什么。
这是我的尝试:
\w+(?!\[[0-9]*?\])
这确实匹配了,例如:
- test, 13, tdfv
请注意,我已经删除了不需要的部分,只返回了翻译好的内容。如果您有任何其他问题,请随时提出。
英文:
I got Strings like this:
test.as123[13].tdfv
Parent.child1
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:
([^\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:
\w+(?!\[[0-9]*?\])
This does match for example:
- test, 13, tdfv
答案1
得分: 3
// You can remove all occurrences of digits inside square brackets and then split on a dot:
.replaceAll("\\[\\d+]", "").split("\\.")
// Or, you may directly split on the `(?:\\[\\d+])?\\.` pattern:
.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";
String results[] = s.replaceAll("\\[\\d+]", "").split("\\.");
System.out.println(Arrays.toString(results));
// => [test, as123, tdfv]
String results2[] = s.split("(?:\\[\\d+])?\\.");
System.out.println(Arrays.toString(results2));
// => [test, as123, tdfv]
英文:
You can remove all occurrences of digits inside square brackets and then split on a dot:
.replaceAll("\\[\\d+]", "").split("\\.")
Or, you may directly split on the (?:\[\d+])?\.
pattern:
.split("(?:\\[\\d+])?\\.")
It matches
(?:\[\d+])?
- an optional occurrence of a[
, 1+ digits,]
\.
- a dot.
See the Java demo online:
String s = "test.as123[13].tdfv";
String results[] = s.replaceAll("\\[\\d+]", "").split("\\.");
System.out.println(Arrays.toString(results));
// => [test, as123, tdfv]
String results2[] = s.split("(?:\\[\\d+])?\\.");
System.out.println(Arrays.toString(results2));
// => [test, as123, tdfv]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论