简体   繁体   中英

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
    • \\S require a non-space character (so we don't match like * def* in abc def )
    • (?:\\S| \\D) either a non-space character or a space and a non-digit
    • * 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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