Can't define regex pattern for requirements (javascript split pattern)
I am trying to figure out the regex pattern for the next line and requirements.
this. i s.a.string .but. so is . this
Expected Result:
1 - "this. i s"
2 - "a"
3 - "string .but. so is . this"
The split must be done by .
, but if it has a space before or after , then it must be part of the previous result.
I am trying the following options (with results)
/[(^?=\.]+|[^?<=\.]+/g
1 - "this"
2 - "."
3 - " i s"
4 - "."
5 - "a"
6 - "."
7 - "string"
/[^?<=\.]+/g OR /[^\.]+/g
1 - "this"
2 - " i s"
3 - "a"
4 - "string"
Edit: updated line and expected results. Based on the ambiguity I saw in the comments / answers that have been removed.
+3
source to share
3 answers
You can try something like this:
Logics:
- Find the pattern
not space
followed.
, thennot space
and replace the firstnot space
withnot space|
- Now split with
|.
to get a list of groups
function getGroups(str){
var replaceRegex = /(\S)(?=\.\S)/g;
var g = str.replace(replaceRegex, "$1|").split("|.");
console.log(g)
return g;
}
getGroups("this. i s.a.string");
getGroups("this . i s.a.string");
getGroups("this . i 1.a.string");
getGroups("127.0.0.1");
0
source to share
With lookahead
and the lookbehind
split regex would be:
(?<! )\.(?! )
But JavaScript doesn't support appearance, one trick:
var s = "this. i s.a.string .but. so is . this";
s.replace(/([^ ])\.(?! )/g, "$1__special__").split("__special__")
- Replace the separators with
lookahead
and the group capture behind with a custom separator - Split into a new special delimiter
0
source to share