3

i have a string with a single character and a digit, for eg J0. I have to write an expression to remove 0 and keep only that single character.

5
  • regex : \d replacement string : empty string. Commented Mar 10, 2015 at 11:37
  • I did the same way, but that deletes all. I want to delete only 0 and keep J as it is. eg : J0 to J. Commented Mar 10, 2015 at 11:39
  • what do you mean by it deletes all? Could you provide an exact example? or replace 0 with empty string. Commented Mar 10, 2015 at 11:40
  • I have used like this name.replaceAll("([A-Z][0-9])","") and my output is blank. what i want is when i give J0 i need J. J0 is my input string. Commented Mar 10, 2015 at 11:42
  • Why dont you use just name.replaceAll("([0-9])","") ? [A-Z] will replace chars from A to Z too, that's including J, for instance Commented Mar 10, 2015 at 11:52

2 Answers 2

1

Use a positive lookbehind assertion or capturing group to replace a digit which exists next to an uppercase letter with empty string.

name.replaceAll("(?<=[A-Z])[0-9]", "");

OR

name.replaceAll("([A-Z])[0-9]", "$1");
Sign up to request clarification or add additional context in comments.

1 Comment

or name.replaceAll("[0-9]$", "");
0

I tried in Python using regular expression With your assumption that you have a string with a single character and a digit, for eg J0

>>> import re
>>> x = re.search('(\w)\d', 'j0')
>>> x.groups()
('j',)
>>> x.groups()[0]
'j'

You can use the pattern (\w)\d

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.