英文:
How to compose regex with condition in Java?
问题
条件:
- 数字可以是整数或小数(共8位数字)
- 数字只能由空格(一个或多个)和逗号(0个或一个)分隔
- 逗号只能在数字内部(一行开头和结尾不能有逗号)
- 一行开头可能有空格(一个或多个)
- 一行结尾可能有空格(一个或多个)
我的做法:
([\s]*\d+(\.{1}\d+)?[\s\,\s]+){7}(\d+(\.{1}\d+)?[\s]*){1}
^ 这里 ^
这基本上是正确的,但有一个例外情况。在以下字符串中,我得到的是true
,但需要的是false
:
String s1 = " 0 , 4.4 3.2,, 4.1 2 4 1 7.7";
我不能这样做:
> 数字之间可以用一个逗号分隔,或者没有逗号,但在这种情况下,必须有一个空格(一个或多个)。
英文:
Condition:
- numbers can be either int or double (total 8 digits)
- numbers can only be separated by spaces (one or many) and commas (0 or one)
- commas can only be inside numbers (there can be no commas at the beginning and end of a line)
- there may be spaces at the beginning of the line (one or many)
- there may be spaces at the end of the line (one or many)
What I do:
([\s]*\d+(\.{1}\d+)?[\s\,\s]+){7}(\d+(\.{1}\d+)?[\s]*){1}
^ this ^
That's ok, except for one condition.
On this string I get true
, but need false
:
String s1 = " 0 , 4.4 3.2,, 4.1 2 4 1 7.7";
I can't do this:
> Numbers can be separated by only one comma or no comma, but in this case there must be a space (one or many).
答案1
得分: 1
这是我针对空格/逗号情况提出的解决方案(还删除了一些多余部分):
Pattern.compile("([\\s]*\\d+(\\.\\d+)?(?:\\s*,\\s*|\\s+)){7}(\\d+(\\.\\d+)?[\\s]*)");
根据你提供的示例,似乎可以达到你的要求。(你在使用 {1}
的地方通常是隐含的,所以我去掉了这些)
英文:
This is the one I came up with for the spaces/commas (also removed some redundant parts):
Pattern.compile("([\\s]*\\d+(\\.\\d+)?(?:\\s*,\\s*|\\s+)){7}(\\d+(\\.\\d+)?[\\s]*)");
Seems to do what you want with the sample you provided, at least. (The use of {1}
is generally implied for the places you used it, so I removed those)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论