Java正则表达式替换由非字母数字字符包围的字符串 [英] Java Regex to replace string surrounded by non alphanumeric characters

查看:48
本文介绍了Java正则表达式替换由非字母数字字符包围的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来替换句子中的单词,例如某事".我需要用 "hello, something" 替换它.str.replaceAll("hi", "hello") 给了我 "hello, somethellong".

I need a way to replace words in sentences so for example, " something". I need to replace it with "hello, something". str.replaceAll("hi", "hello") gives me "hello, somethellong".

我也试过 str.replaceAll(".*\\W.*" + "hi" + ".*\\W.*", "hello"),我在这里看到了另一个解决方案,但似乎也不起作用.

I've also tried str.replaceAll(".*\\W.*" + "hi" + ".*\\W.*", "hello"), which I saw on another solution on here however that doesn't seem to work either.

实现此目的的最佳方法是什么,因此我只替换未被其他字母数字字符包围的单词?

What's the best way to achieve this so I only replace words not surrounded by other alphanumeric characters?

推荐答案

在这种情况下,单词边界应该很适合您(IMO 是更好的解决方案).更通用的方法是使用负前瞻和后视:

Word boundaries should serve you well in this case (and IMO are the better solution). A more general method is to use negative lookahead and lookbehind:

 String input = "ab, abc, cab";
 String output = input.replaceAll("(?<!\\w)ab(?!\\w)", "xx");
 System.out.println(output); //xx, abc, cab

这将搜索在另一个单词字符之前或之后没有出现的ab".您可以将\w"替换为任何正则表达式(好吧,由于正则表达式引擎不允许无限制环视,因此存在实际限制).

This searches for occurrences "ab" that are not preceded or followed by another word character. You can swap out "\w" for any regex (well, with practical limitations as regex engines don't allow unbounded lookaround).

这篇关于Java正则表达式替换由非字母数字字符包围的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆