How to match this pattern [closed] - javascript

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 this pattern amongst a large garble of HTML:
<td>SIP/159#PBX</td>
I want to match this, getting:
159
as the result. This pattern will always be the same, with the only difference being the number between the "/" and the "#".
I have no idea how to do this in JS Regex. Any ideas?

The regex you can use is like this:
/SIP\/(\d+)#PBX/
This finds:
text SIP
followed by a / (which is escaped so it isn't interpreted as the end of the regex)
followed by one or more digits (captured in a group delineated with parens)
followed by the text #PBX
And, then you pull out the first matched group if there's a match.
And, if you have nothing else to go on other than it's in a <td> in your page, then you can use this generic code that looks at all <td> elements in the page. Ideally, you would use the structure of the page to more clearly target the appropriate <td> cells.
var tds = document.getElementsByTagName("td");
var regex = /SIP\/(\d+)#PBX/;
for (var i = 0; i < tds.length; i++) {
var matches = tds[i].innerHTML.match(regex);
if (matches) {
var number = parseInt(matches[1], 10);
// process the number here
}
}
Working demo: http://jsfiddle.net/jfriend00/vDwfs/
If the HTML is not in your page, but in a string, then you can just use the same regex to search for it in the HTML string. You could bracket it with <td> and </td> if that seems wise based on your context.
var matches, number;
var regex = /SIP\/(\d+)#PBX/g;
while (matches = regex.exec(htmlString)) {
number = parseInt(matches[1], 10);
// process the number here
}

You can analyze the string with the following regular expression:
var result = "<td>SIP/159#PBX</td>".match("\<td\>SIP\/([0-9]+)\#PBX\<\/td\>");
Then, the numbers you want will be stored in result[1]:
alert(result[1]);
The trick is to surround the part of the string that you want to isolate in parentheses. Then, the result of the match function is an array in which the first element is the whole string matched by the regular expression, then a new element for each group enclosed in parentheses.

Assuming you have the string stored in a variable named html
html.match(/SIP\/([0-9]*)\#PBX/g)

try this: "SIP/159#PBX".match(/[^\/]+\/([^#]+)#[\s\S]*/)[1]

Related

Remove consecutive zeroes from an numeric string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
This post was edited and submitted for review 14 days ago.
Improve this question
I have an <input type='number'/> element.
I would like to perform a transformation on the number that is input when the submit event triggers. It could be on another event also: I'm open to suggestions, but the transformation should not happen while the user is typing, only when they finish their input.
The transformation should be as follows:
Remove all leading zeros
Remove all ending zeros
Replace all other consecutive zeroes with just one or two zeroes (depending on a variable it should be one or two)
For example: 01002000400 will be converted to 10204
The third rule depends on a boolean variable first_user: if it's true then all inside consecutive zeroes will be converted to one zero, if it's false all inside zeroes will be converted to two zeroes.
Attempt
Here is what I've tried:
ref.value.replace('/^0+/', '')
To also remove the ending zeroes, I tried ^0$, but it didn't work out as I intended: there was no effect.
And I have no idea how to implement the third rule.
How can I achieve this?
You can do this with a single replace call. The three cases can be checked in this order:
Zeroes at start of string
Zeroes at end of string
Zeroes (more than one) anywhere else: capture the first zero in capture group
As replacement, output the string captured by the capture group. As this group only captures a zero when the third case kicks in, this practically means that all other zeroes are removed.
I believe an exception to this rule has to be introduced for when the number is exactly 0. I guess you want to keep that single zero then. To make that happen, I would restrict the first two rules as follows:
Zeroes at start of string when followed by a non-zero
Zeroes at end of string when following a non-zero
Zeroes (more than one) anywhere else: capture the first zero in capture group
The third case will now also apply when the input consists of only zeroes.
You could use the submit event, but maybe it is interesting too to use the change event: it does not trigger while the user is typing, but does trigger when the user "commits" the value, i.e. when focus is moved to another element, or another tab/window is selected, or the up/down controls are used on the input widget, or the form is submitted, ...
const inputDouble = document.getElementById("double")
const input = document.getElementById("inp");
document.addEventListener("change", function () {
const regex = inputDouble.checked
? /^0+(?=[^0])|(?<=[^0])0+$|(00)0+/g
: /^0+(?=[^0])|(?<=[^0])0+$|(0)0+/g
input.value = input.value.replace(regex, "$1");
});
<input id="double" type="checkbox"> Double zeroes<br>
Number to clean: <input id="inp" type="number"><br>
<button>Fake submit</button>
A good solution would be to implement a simple algorithm that does what you need. Example:
Remove from the first position (0) on until you find a non-zero number;
Remove from the last position backwards (string.length-1) until you find a non-zero number;
Walk the string after the modification above and: if the current number is a non-zero create a new string with it, if it is zero and the previous was not, include it on the new string, if the previous was zero, ignore it.
That should make a very simple method and will work better then a regex.
For the onSubmit trigger, I think it will work fine. I would use onChange and store it in a hidden field just, but I thing onSubmit will do the trick
I think you're overthinking it. To replace multiples of anything with a single version of that thing you just need to target one or more things and in your replace function, replace with a single thing
You don't really need to specify the beginning or the end. You just need to specify any one or more 0 and then replace with a single 0
Try this:
const singleZeros = '10020004'.replace(/(0+)/g, '0')
console.log(singleZeros);
For removing the leading and trailing 0's, there might be a better way but off the top of my head, this is what I'd do:
const removeStart = (s) => s.startsWith('0') ? s.slice(1) : s;
const removeEnd = (s) => s.endsWith('0') ? s.slice(0, s.length - 1) : s;
const zerosOnEnds = '0102040'
const zerosTrimmed = removeEnd(removeStart(zerosOnEnds));
console.log(zerosTrimmed)
Maybe a simple solution would be to create a conversion function to run on submit. Something like:
answer = 10020004
function transform(answer){
final_answ = ''
index = 0
zero_index = -2
while(index<answer.toString().length){
if (answer.toString()[index] !== '0'){
final_answ += answer.toString()[index]
} else if (index === zero_index+1){
zero_index = index
} else {
final_answ += answer.toString()[index]
zero_index = index
}
index++
}
}
Transforming the user response to string will also make it easy for you to remove starting and ending '0'.
If this does not help will you please, provide more information?
Hope it helps.
You can try this
let str = '001002000400'
str = str.replace(/^0*(\d+?)0*$/, (matchs, p1) => {
return p1.replaceAll(/([^0]+)0+/g,'$10')
})
console.log(str); //10204
from your post all you need is just a regex to replace first zero with empty string and other zero in middle if they're more than 1 replace them and just keep one
what you will be need first thing in your code you're used the regex as string'/^0+/' and that's not the true way to use regex you should remove the string quotes and write your regex inside forward slash / like /regex/
second: you need to use regex modifiers in your case you need g modifier
for more info about regex you can check some tutorials like that or quick reference like w3schools reference
here's your regex
//Result: 104057
console.log("0100400057".replace(/^0|(0)+(?=0)/g, ""))

How to match numbers followed by any combination of special characters and spaces using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am a newbie with regex and I am having trouble trying to match some parts of a string so I can remove it from a piece of entered text. I want to match digits followed by a sequence of a combination of any special characters + spaces. There could also be non Latin characters that should not be removed inside the sequence (for example Ñ).
for example inputted it may look like:
11#- &-.text
11 $ab*cÑ .somewords123
outputted I would expect
text
abcÑsomewrods123
I am using javascript replaceall method with regex to find it. So far I have something basic like this regex
.replaceAll(/\d+(\#|\s)+(\-|\$)+(\s|\&)+(\&)+(\-)+(\.)/g, '');
Is there a way to write this more efficiently so that it captures any special characters since the text can contain more different special chars than in the examples? Or is this a situation better handled with pure JS?
Thanks in advance for your help.
You should ether have blacklist of what you calling special characters, or whitelist of the allowed characters.
for blacklist it gonna look like:
const blacklist = "!##$%^&*()_+.";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[${blacklist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));
for whitelist it gonna looks like:
const whitelist = "0-9a-zA-Z";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[^${whitelist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));

split a string with comma and colon [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a string like as shown below:
var String = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"
Where xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx represents an alphanumeric generated Id and after the colon is a string related to that Id.The string can be a string with comma or without comma.What I wanted was that I wanted to split the string such that I get an array with ID:its corresponding string , just like shown below.
["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma",
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"]
HOW I ACCOMPLISHED THIS
I used the javascript split function where i split the string by comma followed by 36 characters (for ID) and colon.
String.split(/,(?=.{36}:)/);
PS: I apologize as previously I was not able to ask the question in the correct manner.Hope this time people understand it.
You could use String#split by comma and a look ahead for numbers and colon.
var x = "123456:a,b,c,435213:r,567876:e,363464:t,y,u";
array = x.split(/,(?=\d+:)/);
console.log(array);
For alphanumeric values
var x = "1A3456:a,b,c,43Y213:r,567W76:e,363x64:t,y,u";
array = x.split(/,(?=[a-z0-9]+:)/i);
console.log(array);
You can use the method .split(). I used the "$" as a split sign instead of "," because i thought you would like to keep them.
var values = "123456:a,b,c$435213:r$567876:e$363464:t,y,u".split("$");
var x = values[0];
console.log(values)

Tricky RegEx Capture [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.
var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);
This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.
The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and #.
Any ideas on how to complete this with regex?
It sounds like the content between quotes is any character except for a quote, in which case you can get away with
/"([^"]*)"/
what you're looking for is this with the /g "global flag":
/("[^"]*")/g
In your example, it's like this:
var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);
When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).
If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:
var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
results.push(match[1])
match = r.exec(str);
}
Now, results is ["J", "L"]

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources