Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex from character until end of string

Hey. First question here, probably extremely lame, but I totally suck in regular expressions :(

I want to extract the text from a series of strings that always have only alphabetic characters before and after a hyphen:

string = "some-text"

I need to generate separate strings that include the text before AND after the hyphen. So for the example above I would need string1 = "some" and string2 = "text"

I found this and it works for the text before the hyphen, now I only need the regex for the one after the hyphen.

Thanks.

like image 391
Viktor Avatar asked Mar 14 '11 00:03

Viktor


People also ask

What is the regex pattern for end of string?

+\r?\ Z matches the end of a string, and also matches a string that ends with \n or \r\n .

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do I specify start and end in regex?

The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.


1 Answers

You don't need regex for that, you can just split it instead.

var myString = "some-text";
var splitWords =  myString.split("-");

splitWords[0] would then be "some", and splitWords[1] will be "text".

If you actually have to use regex for whatever reason though - the $ character marks the end of a string in regex, so -(.*)$ is a regex that will match everything after the first hyphen it finds till the end of the string. That could actually be simplified that to just -(.*) too, as the .* will match till the end of the string anyway.

like image 112
Michael Low Avatar answered Oct 19 '22 10:10

Michael Low