I have the following string:
"Group: I_am_group |SubGroup: I_am_subgroup"
And the following regex:
Group:\s(?<group>\w ) \|SubGroup:\s(?<subGroup>\w*)
The result is:
Until here- it's perfect to me, but when I am having the following case:
for the following strings:
1. "Group: I_am_group |SubGroup:"
2. "Group: I_am_group |"
3. "Group: I_am_group"
I want to get the result (e.g. for the string "Group: I_am_group"):
Match1 Group: I_am_group
group I_am_group
subGroup null
Is it possible with regex to create an empty group when it's not found? or give a default value to a group if the value not found?
In this case, I want to create the group named- 'subGroup' on the result with the value- null.
CodePudding user response:
Unmatched groups per spec have value undefined
, not null
. A named group is unmatched, for example, when it appears inside another optional group that is unmatched.
Now take your three example strings that should produce an empty group and compare them with the original string "Group: I_am_group |SubGroup: I_am_subgroup"
.
- In string (1.),
" I_am_subgroup"
is missing. That's\s(?<subGroup>\w*)
in the regular expression. - In string (2.),
"SubGroup: I_am_subgroup"
is missing. That'sSubGroup:\s(?<subGroup>\w*)
in the regular expression. - In string (3.),
" |SubGroup: I_am_subgroup"
is missing. That's\|SubGroup:\s(?<subGroup>\w*)
in the regular expression.
By enclosing all three of these parts in an optional group, we get
/Group:\s(?<group>\w )( \|(SubGroup:(\s(?<subGroup>\w*))?)?)?/
This is a regular expression that matches in all cases with an empty match for subGroup
. Note though that \w*
can be replaced with \w
, unless you would like subGroup
to be an empty string (not undefined
) in cases when all other parts are present.
const regExp = /Group:\s(?<group>\w )( \|(SubGroup:(\s(?<subGroup>\w ))?)?)?/;
const str1 = "Group: I_am_group |SubGroup:";
const str2 = "Group: I_am_group |";
const str3 = "Group: I_am_group";
console.log(str1.match(regExp).groups);
console.log(str2.match(regExp).groups);
console.log(str3.match(regExp).groups);