简体   繁体   中英

Regular Expression remove leading blank and dash character

Given a string like String a="- = - - What is your name?";

How to remove the leading equal, dash, space characters, to get the clean text,

"What is your name?"

If you want to remove the leading non-alphabets you can match:

^[^a-zA-Z]+

and replace it with '' (empty string).

Explanation:

  • first ^ - Anchor to match at the begining.
  • [] - char class
  • second ^ - negation in a char class
  • + - One or more of the previous match

So the regex matches one or more of any non-alphabets that are at the beginning of the string.

In your case case it will get rid of all the leading spaces, leading hyphens and leading equals sign. In short everything before the first alphabet.

 $a=~s/- = - - //;

In Javascript you could do it like this

var a = "- = - - What is your name?";
a = a.replace(/^([-=\s]*)([a-zA-Z0-9])/gm,"$2");

爪哇:

String replaced = a.replaceFirst("^[-= ]*", "");

Assuming Java try this regex:

 /^\W*(.*)$/

retrieve your string from captured group 1!

\\W* matches all preceding non-word characters
(.*) then matches all characters to the end beginning with the first word character

^,$ are the boundaries. you could even do without $ in this case.

Tip try the excellent Java regex tutorial for reference.

In Python:

>>> "- = - - What is your name?".lstrip("-= ")
'What is your name?'

To remove any kind of whitespace, use .lstrip("-= \\t\\r\\n") .

In Javascript, I needed to do this and did it using the following regex:

^[\s\-]+

and replace it with '' (empty string) like this:

yourStringValue.replace(/^[\s\-]+/, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM