I would like to keep 456
with a regex from the following string:
john#456 18 mai 2017 11:01
I tested with
#(.*)
But I keep 456 18 mai 2017
.
I would like to keep 456
with a regex from the following string:
john#456 18 mai 2017 11:01
I tested with
#(.*)
But I keep 456 18 mai 2017
.
You can use the following regex, that will extract the number after your #
:
.+#(\d+ )
Tested on the following data:
john#456 18 mai 2017 11:01
test123#123 18 mai 2017 11:01
michael#4561218 mai 2017 11:01
'(çà'_(fdlfsnd#456 18 mai 2017 11:01
lrjdlfddfdf#456 18 mai 2017 11:01
The regex extracts:
456
123
4561218
465
465
Javascript solution:
const regex4id = /.+#(\d+)/g;
var text = "john#456 18 mai 2017 11:01"
var id = text.match(regex4id);
if(id != null) {
p = regex4id.exec(text);
console.log("p: " + p[1]);
}
Using Lookahead and Lookbehind:
To get left of # and before the next space, you could also use a positive lookbehind and lookahead if you wanted it as a full match without using capturing groups:
(?<=#)\w+(?=\s)
(?<=#)
is a positive lookbehind which ensures that #
preceeds the match\w+
matches one or more characters (includes alphabets, numbers and underscore)(?=\s)
is a positive lookahead which ensures that a space \s
follows the matchLearn more about lookaheads and lookbehinds here.
Using a capturing group:
You can also do it faster using a capturing group instead of lookaheads and lookbehinds. (Though the difference is negligible when only performing it for one match)
#(\w+)\s
Here, you can extract it by referring to group 1 based on your language $1
or group[1]
#
represents literal #
(\w+)
represents one or more characters in a capturing group (which is the 1st capturing group\s
represents a single spaceHope this helps!