java Regex:用一个数字替换所有数值 [英] java Regex: replace all numerical values with one number
问题描述
我有一行简单的文本,其中可能包含诸如12.3"或1983"或5/8"之类的数字.每当出现任何数字时,我只需要用固定字符替换,比如数字8".
I have a simple line of text which might include numbers like "12.3" or "1983" or "5/8". Whenever any number appears, I just need to replace with a fixed character, say the digit "8".
我一直在使用 Java 中的 Regex,像这样:
I've been fiddling about with Regex in Java, with things like this:
String line = str.replaceAll("[0-9]+/*.*[0-9]*", "8");
但无济于事.
知道正确的模式应该是什么吗?
Any idea what the correct pattern should be?
推荐答案
试试这个表达式:(?>-?\d+(?:[\./]\d+)?)
,请记住,在 Java 字符串中,您需要对反斜杠进行转义,即您会得到 "(?>-?\\d+(?:[\\./]\\d+)?)"代码>
Try this expression: (?>-?\d+(?:[\./]\d+)?)
, keep in mind that in Java strings you need to escape the backslashes, i.e. you'd get "(?>-?\\d+(?:[\\./]\\d+)?)"
以下是表达式的细分:
封闭的
(?>...)
是一个原子组,用于防止灾难性的回溯.对于简单或短字符串,它也可以工作.
The encloseing
(?>...)
is an atomic group to prevent catastrophic backtracking. For simple or short strings it would work without as well.
-?
负数的潜在减号
\d+
任何数字序列(至少一个)
\d+
any sequence of digits (at least one)
(?:[\./]\d+)?
一个可选的非捕获组,由一个点组成(注意这里不需要转义,它是只是为了一致性)或斜线后跟至少一位数字.
(?:[\./]\d+)?
an optional non-capturing group consisting of either a dot (note that you don't need to escape it here, it's just for consistency) or a slash followed by at least one more digit.
更新
如果你不想替换数字",比如.1234
、1234.
/1
或 5/
(左边或右边缺少一个数字),试试这个表达式:(?>(?<![\d\./])-?\d+(?:(?:[\./]\d+)|(?![\d\./])))
If you don't want to replace "numbers" like .1234
, 1234.
/1
or 5/
(a digit is missing either left or right), try this expression: (?>(?<![\d\./])-?\d+(?:(?:[\./]\d+)|(?![\d\./])))
这里再次细分:
封闭的
(?>...)
是一个原子组,用于防止灾难性的回溯.对于简单或短字符串,它也可以工作.
The encloseing
(?>...)
is an atomic group to prevent catastrophic backtracking. For simple or short strings it would work without as well.
(?<![\d\./])
匹配不能直接跟在数字、点或斜线后面 - 请注意,不跟在数字约束是需要的匹配数字的开头,否则你将匹配 .1234
(?<![\d\./])
the match must not directly follow a digit, dot or slash - note that the not follow a digit constraint is needed to match at the start of the number, otherwise you'd match 234
in .1234
-?
负数的潜在减号
\\d+
任何数字序列(至少一个)
\\d+
any sequence of digits (at least one)
(?:(?:[\./]\d+)|(?![\d\./]))
匹配必须后跟一个点或斜线至少一个数字或者后面不能跟一个数字、点或斜线,这将匹配 1.0
但不匹配 1.
- 注意后面不能跟一个需要数字约束来防止 1234 中的
123
匹配.
(?:(?:[\./]\d+)|(?![\d\./]))
the match must either have a dot or slash followed by at least one digit or must not be followed by a digit, dot or slash, this would match 1.0
but not 1.
- note that the not to be followed by a digit constraint is needed to prevent matching 123
in 1234.
这篇关于java Regex:用一个数字替换所有数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!