-1

I'd like to find a regex expression to remove numbers from string Only if the char before any number is not alphabetic or is a whitespace. For instance:

_123
(1234
.12345
?!8
hi 123
?? 1234

will be

_
(
.
?!
hi
??

on the other hand:

aaa123
A1234
Z_L12345
..A8
aaa a123

will be:

aaa123
A1234
Z_L12345
..A8
aaa a123

Any ideas?

Thank you!

4
  • @vks I thought the language was not necessary, I'm using PHP. Edited. Commented Oct 18, 2014 at 7:31
  • char before any number is not alphabetic then how come A1234 became A? Commented Oct 18, 2014 at 7:33
  • Refer stackoverflow.com/questions/3363005/… stackoverflow.com/questions/7847223/… Commented Oct 18, 2014 at 7:34
  • sorry, it's corrected now Commented Oct 18, 2014 at 7:38

3 Answers 3

1
[ ]\d+|(?<=[^a-zA-Z0-9\n])\d+

Try this.Replace with empty string.See demo.

http://regex101.com/r/mE6hO4/5

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I forgot to add this: 123 hi will remain 123 hi, how can I do that too?
1

use the lookbehind assertion for this, for example for your case use look behind for behind of your match case, it can't be "A-Z" or "a-z" or "0-9" then you should create a set from these and insert it to look-behind.

this is your regex

(?<=[^a-zA-Z0-9])\d+

and this is your demo

http://regex101.com/r/dN8sA5/21

then you should replace it with NULL string.

Edit: it's very better to Trim your final string with one of these approach

  1. Use Regex: \s*(?<=[^a-zA-Z0-9])\d+\s*
  2. Use Trim: after the replacing your string, use String.Trim for removing arounding space with the string.

I really prefer the first approach...

for more information about look-behind see this:

http://www.regular-expressions.info/lookaround.html

Comments

1

Search for this regex:

([^a-zA-Z0-9])(?!^)\d+

Replace by:

$1

RegEx Demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.