Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to remove everything but characters and numbers

Tags:

java

regex

I would like to remove everything but the Characters a-z,A-Z and 0-9 from a String so I need to create a regular expression for Java's string.replaceAll(regex, "");

The old string would look like this:

MAX EUK_1334-PP/B+ 

The new string should look like this:

MAXEUK1334PPB 
like image 773
Dominik Avatar asked Jun 04 '11 20:06

Dominik


People also ask

How do you remove everything but letters from a string?

To remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string, we can use the JavaScript string's replace method. We call text. replace with a regex that matches all characters that aren't letters and numbers and replace them with empty strings.

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What is ?= * In regular expression?

. Your regex starts with (?= (ensure that you can see, but don't consume) followed by . * (zero or more of any character).

Which regexp pattern and function can be used to replace special characters and numbers in a string?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")


2 Answers

There's probably a more concise regex, but this will certainly work:

string.replaceAll("[^a-zA-Z0-9]", ""); 
like image 118
stevevls Avatar answered Sep 21 '22 02:09

stevevls


string.replaceAll("[^a-zA-Z0-9]+", ""); 
like image 22
bw_üezi Avatar answered Sep 22 '22 02:09

bw_üezi