Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace all leading characters not a-Z

Tags:

java

regex

I need to replace all non-letter characters that appear at the start before any letter for example

$ %5hello w8r^ld becomes hello w8r^ld

This regex I got now works greate for replacing none word characters but does not replace numbers

s.replaceFirst("^[\\W_]+", "")
like image 623
code511788465541441 Avatar asked Nov 25 '25 14:11

code511788465541441


1 Answers

You are using the wrong character class. Use

s.replaceFirst("^[^a-zA-Z]+", "")

That is

^          start at the beginning of the string
[^  ]+     one or more (greedy - keep going until you hit a letter
a-zA-Z     ascii characters between a-z or A-Z

Following comments from @anubhava, I changed the * to a +. If you have no match, there is nothing that needs replacing. It's actually cleaner.

like image 153
Floris Avatar answered Nov 28 '25 02:11

Floris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!