简体   繁体   English

正则表达式:如何拆分和替换包含数字的字符串?

[英]Regex: How to split and replace a string that contains numbers?

I need a regex to add an asterisk ( * ) at the beginning and at the end of a word or group of words, except numbers that are alone. 我需要一个正则表达式在一个单词或一组单词的开头和结尾添加一个星号( * ),除了单独的数字。 Any number that has a letter next to it is okay. 任何旁边都有字母的数字都可以。 It's hard to explain, but here we have some examples: 这很难解释,但这里我们有一些例子:

123 Ballister 1 Block           --> 123 *Ballister* 1 *Block*

B@llister Place 123 Block N2 45 --> *B@llister Place* 123 *Block N2* 45

123 B@llister# abc              --> 123 *B@llister# abc*

I tried with: 我尝试过:

 var sample = "@sample 22 @sample2 xyz1"; var x = sample.replace(/[^0-9 ]+/g, function(str) { return "*"+str.trim()+"*"; }); 

but it is not working. 但它不起作用。 I hope somebody can help me. 我希望有人可以帮助我。

Here's an example that works: 这是一个有效的例子:

/((?!\d+\b)\S(?:\S| \D)*)/

The replacement string is just 替换字符串就是

*$1*

Here's a demo . 这是一个演示

The examples work like this: 这些例子的工作方式如下:

123 Ballister 1 Block
--> 123 *Ballister* 1 *Block*

B@llister Place 123 Block N2 45
--> *B@llister Place* 123 *Block N2* 45

123 B@llister# abc
--> 123 *B@llister# abc*

@rmani empory 123
--> *@rmani empory* 123

#1smple 22 #sample2 #xyz1
--> *#1smple* 22 *#sample2 #xyz1*

Explanation 说明

We want to match whole words or groups of words, but exclude words that are made entirely of digits. 我们希望匹配整个单词或单词组,但排除完全由数字组成的单词。 So... 所以...

  • ( start capturing (开始捕捉
    • (?!\\d+\\b) don't match an entire word of numbers (?!\\d+\\b)与整个数字不匹配
    • \\S require a non-space character (so we don't match like * def* in abc def ) \\S需要一个非空格字符(所以我们不匹配abc def * def*
    • (?:\\S| \\D) either a non-space character or a space and a non-digit (?:\\S| \\D)非空格字符或空格和非数字
    • * zero or more times *零次或多次
  • ) stop capturing )停止捕捉

Putting it All Together 全部放在一起

You can use this as follows: 您可以按如下方式使用:

var sample = "@sample 22 @sample2 xyz1";
var x = sample.replace(/((?!\d+\b)\S(?:\S| \D)*)/g, '*$1*');

Live Demo: 现场演示:

 var input = document.getElementsByTagName('input')[0], output = document.getElementsByTagName('span')[0]; input.onkeyup = function (elem) { output.innerHTML = input.value.replace(/((?!\\d+\\b)\\S(?:\\S| \\D)*)/g, '*$1*'); }; 
 <p> Original Text: <input /> </p> <p> Replacement: <span /> </p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM