I have a string that can optionally contain "ob_" in the beginning and optionally "~..." in the end, examples:
ob_name
name
ob_name~213334dsf34n
name~kjdsf8943j
In each case, I want to get name
returned. However, I don't get the RegEx to work. I tried using
/^(ob_)?(. )(~. )?$/
of which I thought it reads like "ob_ in the beginning contained zero or one times, string sequence in the midde, ~ plus random chars in the end".
What do I do wrong?
CodePudding user response:
If you don't need to catch the ob_
or ~xxx
, you can try:
$s = 'ob_name~213334dsf34n';
if (preg_match('/^(?:ob_)?(. ?)(?:~. )?$/',$s,$matches)) {
var_dump($matches[1]); // this is the name you want
}
CodePudding user response:
Match returns an array, where each index is represented by the ()'s in your regexp.
/^(ob_)?(. ?)(~. )?$/i
(ob_) = index 0
(. ?) = index 1
(~. ) = index 2
So to get the value, you'd do a match on the string, which returns an array,
var myStr = "ob_name~213334dsf34n";
var match = myStr.match(/^(ob_)?(. ?)(~. )?$/i);
... then you'd grab index "2":
var result = match[2]; // "name"
... be careful, this regexp can return match when ob_ and ~ not present, so some extra processing will be needed:
var myStr = "ob_name~213334dsf34n";
var match = myStr.match(/^(ob_)?(. ?)(~. )?$/i);
// match[0] = "ob_name~213334dsf34n"
// match[1] = "ob_"
// match[2] = "name"
// match[3] = "~213334dsf34n"
var result;
if(match){
if( (match[0] && match[0].indexOf("ob_")) > -1 || (match[3] && match[3].indexOf("~") > -1 ){
result = match[2];
}
}
console.log(result || "not found")
test cases:
var cases = [
"ob_name",
"name",
"ob_name~213334dsf34n",
"name~kjdsf8943j",
"bob",
"sally"
];
for(var i=0; i<cases.length; i ){
var match = cases[i].match(/^(ob_)?(. ?)(~. )?$/i);
var result = null;
if(match){
if( (match[0] && match[0].indexOf("ob_")) > -1 || (match[3] && match[3].indexOf("~")) > -1 ){
result = match[2];
}
}
//console.log(match)
console.log(result || "not found")
}
CodePudding user response:
I think you're all overthinking this.
(ob_)?([^~] )
Using preg_match, the desired match will be stored in [2].
Foul