Reputation: 1
I am new to regular expressions. I am trying to use JavaScript regular expressions to extract the last substring within parentheses from a string. It's not working for me. Instead, I'm getting the first substring within a pair of parentheses. Can someone help me?
Here's an example. I am trying to extract the substring 'xyz', but instead I'm getting 'abc'.
var str1 = 'Hello World (abc)'; // May or may not contain parentheses
var str2 = '(xyz)'; // Definitely contains parentheses
var troublesomeString = str1 + ' ' + str2; // This is the string I'm working with
var result = myFunc(troublesomeString);
alert(result); // Should say 'xyz', but instead says 'abc'
...
function myFunc(troublesomeString) {
// Here I am trying to get '(xyz)', but am instead getting '(abc) (xyz)'
var resultArray = troublesomeString.match(/\(.+\)$/);
troublesomeString = resultArray[0];
// Here I am trying to get 'xyz', but am instead getting 'abc'
resultArray = troublesomeString.match(/[a-z]+/); // Adding a $ after + doesn't help
troublesomeString = resultArray[0]; // resultArray[1] is null
return troublesomeString;
}
Upvotes: 0
Views: 1253
Reputation: 20440
You need to add \(
and \)
:
resultArray = troublesomeString.match(/\([a-z]+\)$/);
And the result is ["(xyz)"]
, Note the $
there.
If you want to group
out something, you should wrap ()
to them :
resultArray = troublesomeString.match(/\(([a-z]+)\)$/);
Note the ( )
pair.
the result is ["(xyz)", "xyz"]
And you know what to do next.
Upvotes: 1
Reputation: 2851
You need to use the "g" switch to perform a global search.
Here's a working example:
<script type="text/javascript">
var str = "test (abc) (xyz)";
var result = str.match(/\([^)]+\)/g);
alert(result[result.length - 1]);
</script>
Upvotes: 0
Reputation: 596
Try using this regex instead of the first regex you are using: /\([^\(]+\)$/
. The ^\(
tells it to accept any character except a (
.
As a note, you can use this site http://regexpal.com/ to help you build and test regular expressions.
Upvotes: 0
Reputation: 3402
You are matching everything in between the first "(" and the last ")" which must end the string.
Try this instead to match the contents of the last set of parentheses (which still must end the string as per the '$'):
var resultArray = troublesomeString.match(/\([^)]+\)$/);
Upvotes: 3