admin管理员组

文章数量:1302871

I need to check if the number is next to a letter, and if so, add an underscore.

For example:

Grapes23 --> Grapes_23

I've tried for quite a while, but I'm new to regular expressions. I tried this but it doesn't work:

str=str.replace(/([A-z]+)([0-9])/i, '_'); //if number next to letter, add underscore

I'd appreciate any help, thank you!

I need to check if the number is next to a letter, and if so, add an underscore.

For example:

Grapes23 --> Grapes_23

I've tried for quite a while, but I'm new to regular expressions. I tried this but it doesn't work:

str=str.replace(/([A-z]+)([0-9])/i, '_'); //if number next to letter, add underscore

I'd appreciate any help, thank you!

Share Improve this question edited Aug 13, 2012 at 20:13 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked Aug 13, 2012 at 20:06 graygray 1,0181 gold badge21 silver badges33 bronze badges 1
  • First of all, [A-z] will not match what you want it to, [a-zA-Z] will. Second, you are not using the capture groups you set up, you are replacing everything. Third, the + character means one or more but in your case that wouldn't matter, so remove it. Also, the \d special character will match all digits and can take the place of [0-9] – TheZ Commented Aug 13, 2012 at 20:16
Add a ment  | 

3 Answers 3

Reset to default 5

Look for a letter followed by a number:

str = str.replace(/([a-z])(?=[0-9])/ig, '$1_');

http://regexr.?31qsr

How this regular expression works:

  • ([a-z]) is any lowercase letter, wrapping it in parens makes it a "matching group"
  • (?=[0-9]) is a "lookahead". it basically means "followed by [0-9] (any digit)"
  • i means ignore case (otherwise we would have to use [a-zA-Z])
  • g means global, or replace every match it finds (default only replaces the first one)
  • $1 means "first matching group", or the letter that was matched by the first bullet above.

Run str.replace(/([a-zA-Z])(\d)/g,'$1_$2') on your string. This will look for any letter followed by a number, capture both the letter and number (note the parentheses) and then replace them with an underscore between the two. $1 and $2 are callbacks to the captured letter and number found in the regular expression match.

The easiest approach is:

string.replace(/(\D​​​​​​​​​​​​)(\d)/,'$1_$2')

JS Fiddle.

Note that this will only replace the first instance, if you wish to replace all instances, then I'd suggest the above, but with the g (global) flag:

string.replace(/(\D​​​​​​​​​​​​)(\d)/g,'$1_$2')

JS Fiddle.

本文标签: regexJavascript Regexpif a letter is adjacent to a numberadd an underscoreStack Overflow