用“myWord”

时间:2017-01-24 16:37:56

标签: java replace pattern-matching replaceall

例如: 输入String

Input =  "Hello there, How are you? Fine!! @xyz"

,输出为

Output = "Hello there myWord How are you myWord Fine myWord myWord  myWord xyz"

我尝试使用Pattern类和Matcher类,但它只替换了一种类型的模式和str.replace(".","myWord");

2 个答案:

答案 0 :(得分:2)

您可以使用\\s*[^\\w\\s]\\s*

\\s*[^\\w\\s]表示一个或多个空格

^\\w无法捕获\\s\\w

a-zA-Z0-9_表示\\s

String s="Hello there, How are you? Fine!! @xyz"; System.out.println(s.replaceAll("\\s*[^\\w\\s]\\s*", " myWord ")); 平均空间

Hello there myWord How are you myWord Fine myWord  myWord  myWord xyz

输出:

[]

为了避免任何其他特殊字符,不应该替换它,只需将它们添加到\\s*[^\\w\\s:;\\[\\]]\\s*例如const regex = /\s*[^\w\s\]\[;]\s*/g; const str = `Hello there, How are you? Fine!! ; @xyz []`; const subst = ` myWord `; const result = str.replace(regex, subst); console.log(result);中,如@ brso05所示

演示

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

答案 1 :(得分:0)

您可以这样做:

String str = "Hello there, How are you? Fine!! @xyz";
    str = str.replaceAll("[\\{\\.\\?!\"><',/\\\\\\|@#$%^&\\*~`\\-_=+\\}]", "myWord");
    System.out.println(str);

输出:

  

你好,你好吗?你好吗?我是谁?我是谁?我是谁?我爱你好!