Lukasz
Lukasz

Reputation: 946

regex to remove all text before a character

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.

Upvotes: 45

Views: 201631

Answers (8)

A. Kendall
A. Kendall

Reputation: 451

For Notepad++ users who are getting all but one line's results deleted, try this:

^.*_

Check the box for "Wrap around" Uncheck the box for "matches newline" Click "Replace All"

Source: https://www.winhelponline.com/blog/notepad-plus-find-and-replace-text/

Upvotes: 2

Don Koscheka
Don Koscheka

Reputation: 21

If you cast your url as [System.Uri], the localPath field gives you what you want:

$link_url = "https://www.subdomain.domain.com/files
$local_path= [System.Uri]::new($link_url)

Will yield $local_path = /files

Upvotes: 0

Fabiano Soriani
Fabiano Soriani

Reputation: 8562

In Javascript I would use /.*_/, meaning: match everything until _ (including)

Example:

console.log( 'hello_world'.replace(/.*_/,'') ) // 'world'

Upvotes: 2

Hidde
Hidde

Reputation: 11911

I learned all my Regex from this website: http://www.zytrax.com/tech/web/regex.htm. Google on 'Regex tutorials' and you'll find loads of helful articles.

String regex = "[a-zA-Z]*\.jpg";
System.out.println ("somthing.jpg".matches (regex));

returns true.

Upvotes: 0

Kent
Kent

Reputation: 195039

no need to do a replacement. the regex will give you what u wanted directly:

"(?<=_)[^_]*\.jpg"

tested with grep:

 echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg

Upvotes: 4

Fred
Fred

Reputation: 5006

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);
}

...

Upvotes: 7

xanatos
xanatos

Reputation: 111840

Variant of Tim's one, good only on some implementations of Regex: ^.*?_

var subjectString = "3.04_somename.jpg";
var resultString = Regex.Replace(subjectString,
    @"^   # Match start of string
    .*?   # Lazily match any character, trying to stop when the next condition becomes true
    _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

^[^_]*_

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

Upvotes: 98

Related Questions