Split a string using a regex [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like to split the following str into an array that has 2 elements, the first being 'Some words in a sentence', the second being 'ABC' where ABC can be any upper case character.
const str = 'Some words in a sentence (ABC)';
const regex = ?
const arr = str.split(regex);
...
expect(arr[0]).to.eq('Some words in a sentence');
expect(arr[1]).to.eq('ABC');
expect(arr.length).to.eq(2);
Any thoughts would be appreciated.
Cheers,
Paul

The trick with regex is to break it into steps.
You want two elements, that means two groups, e.g. (<-- between these -->))
The easy one is getting the (ABC) at the end -> \((.*?)\)$ (escaped ()'s
And now you can conclude the rest is the other part: (.*?)
Explained:
/---\ is the \((.*?)\)$
Some words in a sentence (ABC)
^---- (.*?) ----^
That should push you in the direction you are looking for, the final part is for you to figure out :)

Goto https://regex101.com/ and try this
/(.*)\(([A-Z]{3})\)/
with your string
'Some words in a sentence (ABC)'
You will get
Match 1
Full match 0-30 `Some words in a sentence (ABC)`
Group 1. 0-25 `Some words in a sentence `
Group 2. 26-29 `ABC`

Related

Regex to evaluate a list of 6 digit numbers separated by commas [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have an input field that I would like users to put in a list of numbers that are 6 digits long. the list the users input will have variable lengths.
Pass
123456, 123457, 156545, 546541, 546541
Pass
123456, 123457
Pass
546541
Fail
12345, 155154
Fail
154s54, 159475, 153456
Fail
154s544, 159475, 153456
The regEx you are looking for is /^\d{6}$/, which matches a 6 digit number and only 6 digit number.
var cases = [
'123456, 123457, 156545, 546541, 546541',
'123456, 123457',
'546541',
'12345, 155154',
'154s54, 159475',
'154s544, 159475, 153456'
];
//Break up numbers in string into array the check each token
//against the regex. If all tokens passes the test, then it
//returns true, else false.
t = cases.map(c => c.split(', ')
.reduce((p, n) => p && !!n.match(/^\d{6}$/), true));
for (let i=0; i < cases.length;i++)
console.log('case:', cases[i], t[i]?'pass':'fail');
Assuming that you are not looking to capture the individual numbers, but just want to validate the input, the following regex should do:
^(\d{6},\s*)*\d{6}$
Breakdown of the regex:
^ beginning of the string
(\d{6},\s*)* zero or more occurrences of a 6-digit number, followed by a comma and optional whitespace
\d{6} a 6-digit number (this is the last and possibly the only one)
$ end of the string
Note that the expression enclosed within parentheses is a capture group. To avoid capture and make it stricter the expression would be written as:
^(?:\d{6},\s*)*\d{6}$
Note the ?: after the first parenthesis. It means match the expression but do not capture it.

Regex: find capitalized words [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How do I find and extract capitalized words of a string with regex?
I would like to:
extract the capitalized words of a string, as an array
extract the last capitalized word of a string, as a substring:
Both with one regex
If I have this:
var str="This is a STRING of WORDS to search";
I would like to get this 1:
allCapWords // = ["STRING", "WORDS"]
and 2:
lastCapWord // = "WORDS"
To extract the words into an array:
var allCapWords = str.match(/\b[A-Z]+\b/g);
-> ["STRING", "WORDS"]
(Here's a Regex101 test with your string.)
To pull the last word:
var lastCapWord = allCapWords[allCapWords.length - 1];
-> "WORDS"
var str="This is a STRING of WORDS to search";
var regObj = /\b([A-Z]+)\b/g;
allCapWords = str.match(regObj);
You can try this regexpr /\b[A-Z]+\b/gor \b[A-Z0-9]+\b/g if you are interested in catch numbers inside the string

Get part of the string using regexp [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've a strings, which can have a text like:
'some text user#t12# some text'
'username#John# some text'
'some text usersurname#Malks#'
'userphoto#1.jpg#'
How do I get a text between # and # symbols?
There's a typical structure of the part of the string to search for - type#variable#
type is a JS variable type, it's placed before the first #.
variable is a text that I need to get.
I'm searching for a regexp, that return variable, that is between #...#.
The problem is, I'm not too familiar with regexp, can you help me please?
You need to use capture groups, basically in a regex anything in brackets will be part of the cpature group, in this case you want to capture all the characters between two hashes. The any amount of characters regex is .* so this is what you want to capture between two hashes. Once you execute it you will find the match as second in the array (the first will be the string with the hashes.
var type = "";
var myString = "some text user#t12# some text";
var myRegexp = new RegExp(type+"#(.*)#","g");
var match = myRegexp.exec(myString);
alert(match[1]); // t12
any other matches between hashes will be in match[2].. match[n]

Regex that searches for a starting character, anything in between, then an ending character? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So basically, I have a hugeee list of values that I copied from my site and would like them as just plain text. I need to create a regex for Javascript that removes the unwanted stuff
Here is what the values look like before hand:
<option value="111122223333">Some text (45)</option>
<option value="345835385390">Some text (10)</option>
<option value="456727235764">Some text (50)</option>
Here is what they need to look like afterwards:
Some text
Some text
Some text
Is this possible with 1 regex, or will many be needed?
My thinking is that a regex looks for < anything in between, and then > could be used on both the opening and closing option tags. Then the regex could be slightly modified to look for opening ( and then closing ) to remove the counter numbers to the left of the 'Some text' string.
Still learing regex, so it would be great if someone could also add a small explanation to their answer so that I could have some understanding of it. Thanks.
You can probably simplify this if you can use a library like jQuery. In that case you can use the text() method of a jQuery object to get the inner text, then run a simple regex to remove the '(xx)' part:
var vals = $('option').map(function() {
return $(this).text().replace(/\s*\(\d*\)$/, '');
});
// vals => ["some text", "some text", "some text"]
here's a fiddle: http://jsfiddle.net/jhummel/U46pH/
if you can't use a library I think you are looking for a regex like:
/<[^>]+>([^\(]+)\(\d*\)<[^>]+>/g
edit
You asked for a regex explanation, let's look at it part by part
/ = start the regex
< = find a '<' character
[^>]+ = find any character that is not a '>' one or more times
> = find a '>' character
( = start a group, anything in the parens will be saved for later
[^(]+ = find any character that is not a '(' one or more times - need to escape it with a backslash because the paren is a reserved character in regex
) = close the group
( = find a '(' char - need to escape it with a backslash again
\d* = find any numbers zero or more times
) = find a ')' character - escaped again
< = find a '<' character
[^>]+ = find any character that is note a '>' one or more times
> = find a '>' character
/ = end the regex
g = regex flag. Means find all the matches don't stop after the first match
If that's all you hope to accomplish then you can use something like:
(>)(.+)(<)
and then grab the second group out of the match.
EDIT: The parentheses are used to denote groups.

regex to remove multiple comma and spaces from string in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string like
var str=" , this, is a ,,, test string , , to find regex,,in js. , ";
in which there are multiple spaces in beginning,middle and end of string with commas. i need this string in
var str="this is a test string to find regex in js.";
i found many regex in forum removing spaces , commas separately but i could not join them to remove both.
Please give explanation of regex syntex to if possible .
Thanks in advance
You can just replace every space and comma with space then trim those trailing spaces:
var str=" , this, is a ,,, test string , , to find regex,,in js. , ";
res = str.replace(/[, ]+/g, " ").trim();
jsfiddle demo
you can use reg ex for this
/[,\s]+|[,\s]+/g
var str= "your string here";
//this will be new string after replace
str = str.replace(/[,\s]+|[,\s]+/g, 'your string here');
RegEx Explained and Demo
Try something like this:
var new_string = old_string.replace(/[, ]+/g,' ').trim();
The regex is simply [, ]+ if we were to break this down the \s means ANY whitespace character and , is a literal comma. The [] is a character set (think array) and the + means one or more matches.
We throw in a /g on the end so that it does a global search and replace, otherwise it'd just do it for one match only.
You should be able to use
str.replace(/,/g," ");
The 'g' is the key, you may need to use [,]

Categories