Regular Expression for getting everything after last slash
No, an ^
inside []
means negation.
[/]
stands for 'any character in set [/]'.
[^/]
stands for 'any character not in set [/]'.
Regular Expression to collect everything after the last /
This matches at least one of (anything not a slash) followed by end of the string:
[^/]+$
Notes:
- No parens because it doesn't need any groups - result goes into group 0 (the match itself).
- Uses
+
(instead of*
) so that if the last character is a slash it fails to match (rather than matching empty string).
But, most likely a faster and simpler solution is to use your language's built-in string list processing functionality - i.e. ListLast( Text , '/' )
or equivalent function.
For PHP, the closest function is strrchr which works like this:
strrchr( Text , '/' )
This includes the slash in the results - as per Teddy's comment below, you can remove the slash with substr:
substr( strrchr( Text, '/' ), 1 );
Regex to get the entire string after last occurrence of # in a string
let myRegex = new RegExp(/^[^]*(#[^]*)$/);
let matches = myRegex.exec("%sdfsdf#\n##sdgsdf\ngdf#sadgofofo#jhjhj\nhjh");
let myResult = matches[1]
The pattern break down is this:
'^' start at the beginning of the string
'[^]*' match everything including line breaks as much as you can including any '#'
'(#[^]*)' group a match of the final '#' and anything following it, including line breaks
'$' to the end of the string
Regex is greedy so it will suck up everything and land on the final '#' using the pattern above.
The '[^]' is used to match on line breaks.
I learned that from the MDN site examples here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Here is a wonderful regular expression testing site if you have not found it yet:
https://regex101.com/
Here is a JS Fiddle of the above solution
https://jsfiddle.net/y8qbe705/
Regex to match everything after the last occurrence of a string
Sorry I did not catch you wanted after:
</p>
Using this:
.*<\/p>(.*)$
You have an array where the second element is what you look for.
Tested code:
var text = '<p>Foo bar bar bar foo</p> <p>Foo bar bar foo</p> This Foo bar foo bar <br>';
var patt = new RegExp(".*<\/p>(.*)$");
var matched = patt.exec(text);
Tester:
http://www.pythontutor.com/javascript.html#mode=edit
Result:
regular expression match everything after the last space with the word of max 2 or 5 characters
You might use a capturing group if you want to capture the value (or make it non capturing (?:
) with a character class and an alternation using |
to match either 2 word chars or match 5 times one of the listed.
^.*\s(\w{2}|[\w/-]{5})$
Regex demo
Note that \s
could also match a newline.
If the /
and -
can not occur 2 times after each other, not at the start or end and there must be at least 1 occurrence of them:
^.*\s(\w{2}|(?=[\w/-]{5}$)\w+(?:[/-]\w+)+)$
Regex demo
Or make the second part of the string optional
^.*\s([a-zA-Z]{2}(?:[/-][a-zA-Z]{2})?)$
Regex demo
How can I match everything that is after the last occurrence of some char in a perl regular expression?
my($substr) = $string =~ /.*x(.*)/;
From perldoc perlre:
By default, a quantified subpattern is "greedy", that is, it will match
as many times as possible (given a particular starting location) while
still allowing the rest of the pattern to match.
That's why .*x
will match up to the last occurence of x
.
Regex - everything after the last occurrence
Without using a group, you could make use of lookarounds:
(?<=\bABC\s)(?!.*\bABC\b).*
(?<=\bABC\s)
Positive lookbehind, assert ABC and a whitespace char to the left(?!.*\bABC\b)
Negative lookahead, assert no occurrence of ABC to the right.*
Match any char 0+ times (or.+
if there should at least be a single character)
Regex demo | Python demo
If you want to support quantifier in the lookbehind assertion, you could use the PyPi regex module. For example
(?<=\bABC \d+ )(?!.*\bABC\b).*
Regex demo | Pyhon demo
Javascript Regex match everything after last occurrence of string
One option would be to match everything up until the last [/quote]
, and then get anything following it. (example)
/.*\[\/quote\](.*)$/i
This works since .*
is inherently greedy, and it will match every up until the last \[\/quote\]
.
Based on the string you provided, this would be the first capturing group match:
\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.
But since your string contains new lines, and .
doesn't match newlines, you could use [\s\S]
in place of .
in order to match anything.
Updated Example
/[\s\S]*\[\/quote\]([\s\S]*)$/i
You could also avoid regex and use the .lastIndexOf()
method along with .slice()
:
Updated Example
var match = '[\/quote]';
var textAfterLastQuote = str.slice(str.lastIndexOf(match) + match.length);
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;
Alternatively, you could also use .split()
and then get the last value in the array:
Updated Example
var textAfterLastQuote = str.split('[\/quote]').pop();
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;
Regex for matching everything after second-to-last backslash
You can use
@"[^\\]+\\[^\\]+$"
See regex demo
The [^\\]+\\[^\\]+$
matches
[^\\]+
- 1 or more symbols other than\
\\
- a literal\
[^\\]+
- 1 or more symbols other than\
$
- end of string.
In C#, a more efficient way to match some substring at the end is using RegexOptions.RightToLeft
modifier. Use it to make this regex search more efficient.
C# demo:
var line = @"0001 Lorem ipsum dolor sit\011 tortor neque\ 0111\interdum magn";
var pattern = @"[^\\]+\\[^\\]+$";
var result = Regex.Match(line, pattern, RegexOptions.RightToLeft);
if (result.Success)
Console.WriteLine(result.Value); // => " 0111\interdum magn"
Just a comparison of the regex effeciency with and without RTL option at regexhero.net:
Related Topics
Preg_Match(); - Unknown Modifier '+'
Regex Backreference to Match Different Values
Symfony2 and Date_Default_Timezone_Get() - It Is Not Safe to Rely on the System's Timezone Settings
Show Results While Script Is Still Executing
How to Check If an Integer Is Within a Range
PHP Return Only Duplicated Entries from an Array
Passing PHP Variable into JavaScript
How to Store the Data in Unicode in Hindi Language
File_Get_Contents - Failed to Open Stream: Http Request Failed! Http/1.1 404 Not Found
Convert Ascii to Utf-8 Encoding
Array_Multisort and Dynamic Variable Options
Laravel Request::All() Should Not Be Called Statically
Converting Object to JSON and JSON to Object in PHP, (Library Like Gson for Java)
Php. How to Use Array_Column with an Array of Objects