Regular expression removes the space character and dash

For a string of type String a="- = - - What is your name?";

How to remove leading equal, dash, space characters to get clear text,

"What's your name?"

+4
source share
6 answers

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

 ^[^a-zA-Z]+ 

and replace it with '' (empty string).

Explanation:

  • first ^ - Anchor to match the beginning.
  • [] - char class
  • second ^ - negation in class char
  • + - one or more previous matches

So, a regular expression matches one or more of any non-alphabets that are at the beginning of a line.

In your case, it will get rid of all leading spaces leading with a hyphen and the leading sign is equal. In short, to the first alphabet.

+5
source
  $a=~s/- = - - //; 
+1
source

In javascript you can do it like this

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

Java:

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

Assuming Java uses this regex:

  /^\W*(.*)$/ 

extracts your row from captured group 1!

\W* matches all preceding characters without words (.*) Then matches all characters at the end starting with the character of the first word

^, $ - borders. you could even do without $ in this case.

Tip try a great Java tutorial for reference.

0
source

In Python:

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

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

0
source

Source: https://habr.com/ru/post/1304138/


All Articles