Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to remove all text before a character

Tags:

regex

Is there an easy way to remove all chars before a "_"? For example, change 3.04_somename.jpg to somename.jpg.

Any suggestions for where to learn to write regex would be great too. Most places I check are hard to learn from.

like image 270
Lukasz Avatar asked Oct 17 '11 12:10

Lukasz


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you delete everything before a character in a string Java?

. trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).

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 does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

^[^_]*_ 

will match all text up to the first underscore. Replace that with the empty string.

For example, in C#:

resultString = Regex.Replace(subjectString,      @"^   # Match start of string     [^_]* # Match 0 or more characters except underscore     _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace); 

For learning regexes, take a look at http://www.regular-expressions.info

like image 177
Tim Pietzcker Avatar answered Oct 12 '22 00:10

Tim Pietzcker


The regular expression:

^[^_]*_(.*)$ 

Then get the part between parenthesis. In perl:

my var = "3.04_somename.jpg"; $var =~ m/^[^_]*_(.*)$/; my fileName = $1; 

In Java:

String var = "3.04_somename.jpg"; String fileName = ""; Pattern pattern = Pattern.compile("^[^_]*_(.*)$"); Matcher matcher = pattern.matcher(var); if (matcher.matches()) {     fileName = matcher.group(1); } 

...

like image 34
Fred Avatar answered Oct 12 '22 00:10

Fred