使用java将非数字周围的单个数字替换为空格
我想用一个字符串中的空格替换围绕alpha字符[a-zA-Z]的单个数字,如下所示使用java将非数字周围的单个数字替换为空格,java,regex,Java,Regex,我想用一个字符串中的空格替换围绕alpha字符[a-zA-Z]的单个数字,如下所示 "Foo 12 Bar" => "Foo 12 Bar" //1 and 2 shouldn’t be replaced "Foo12Bar" => "Foo12Bar" // 1 and 2 shouldn’t be replaced "Foo1Bar" => "Foo Bar" //1 shouldn’t be replaced "Foo2Bar" => "F
"Foo 12 Bar" => "Foo 12 Bar" //1 and 2 shouldn’t be replaced
"Foo12Bar" => "Foo12Bar" // 1 and 2 shouldn’t be replaced
"Foo1Bar" => "Foo Bar" //1 shouldn’t be replaced
"Foo2Bar" => "Foo Bar" //2 shouldn’t be replaced
"Foo 1Bar" => "Foo 1Bar" //1 shouldn’t be replaced(space @ left side)
有什么帮助吗?您可以对字符串对象使用regex
replaceAll
调用。将(?替换为空字符串。您可以将此模式与空格一起用作替换:
(?<=[^0-9\\s])[0-9](?=[^0-9\\s])
(?您可以像这样尝试正则表达式:
public static void main(String[] args) {
String s1= "Foo1Bar";
String s2 = "Foo11bar";
String s3 = "foo1bar2";
String regex = "(?<=[a-zA-Z])\\d(?=[a-zA-Z])";// positive look-behind and positive look-ahead for characters a-z A-Z surrounding digit
System.out.println(s1.replaceAll(regex, " "));
System.out.println(s2.replaceAll(regex, " "));
System.out.println(s3.replaceAll(regex, " "));
}
所使用的正则表达式匹配一个由任何非数字字符包围的数字。因此,整个匹配仅由匹配“\d”的单个数字字符之前和之后的字符替换.为什么最后一个示例没有被替换?到目前为止您尝试了什么。问题是什么请详细告诉我们Hello Casimir,我将更新问题,似乎它是错误的。这里不鼓励只使用代码的答案,因为虽然他们可能严格地回答问题,但他们不会为提问者或未来的用户提供太多的洞察力偶然发现这个问题。鼓励您解释为什么您的解决方案答案是OP的问题在像a1b2c
这样的字符串的情况下不起作用,因为b
将被第一次替换使用a1b
,这会阻止它在b2c
中使用。在这种情况下也是必要的。另外,Java\
是字符串中的特殊字符,因此要创建表示此文本的字符串,您需要将其写成“\\”
,这意味着\d
正则表达式需要写成“\\d”
。最后一件事实际上不是问题,但可能是改进,无论如何,要否定\d
您不需要将其写成[^\d]
,您只需使用\d
。
Foo Bar
Foo11bar
foo bar2
input.replaceAll("([^\\d])\\d([^\\d])", "$1$2");