I try to include ' symbol to Regular Expressions
I use this function
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
text.substring(with: Range($0.range, in: text)!)
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
and this Regular Expressions
let matched = matches(for: "^[‘]|[0-9]|[a-zA-Z]+$", in: string)
when I search I can find numbers and english letters
but not ' symbol
I guess that what you really want is this:
"['0-9a-zA-Z]+"
Note that I have removed the ^ (text start) and $ (text end) characters because then your whole text would have to match.
I have merged the groups because otherwise you would not match the text as a whole word. You would get separate apostrophe and then the word.
I have changed the ‘ character into the proper ' character. The automatic conversion from the simple apostrophe is caused by iOS 11 Smart Punctuation. You can turn it off on an input using:
input.smartQuotesType = .no
See https://developer.apple.com/documentation/uikit/uitextinputtraits/2865931-smartquotestype
Related
I have a textbox that a user can paste into using Ctrl+V. I would like to restrict the textbox to accept just GUIDs. I tried to write a small function that would format an input string to a GUID based on RegEx, but I can't seem to be able to do it. I tried following the below post:
Javascript string to Guid
function stringToGUID()
{
var strInput = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
var strOutput = strInput.replace(/([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/,"$1-$2-$3-$4-$5");
console.log(strOutput );
//from my understanding, the input string could be any sequence of 0-9 or a-f of any length and a valid giud patterened string would be the result in the above code. This doesn't seem to be the case;
//I would like to extract first 32 characters; how do I do that?
}
I suggest that you remove the dashes, truncate to 32 characters, and then test if the remaining characters are valid before inserting the dashes:
function stringToGUID()
{
var input = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
let g = input.replace("-", "");
g = g.substring(0, 32);
if (/^[0-9A-F]{32}$/i.test(g)) {
g = g.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
}
console.log(g);
}
stringToGUID();
(The i at the end of the regex makes it case-insensitive.)
You are already matching 32 characters with the pattern, so there is no need to get a separate operation to get 32 characters to test against.
You can replace all the hyphens with an empty string, and then match the pattern from the start of the string using ^
Then first check if there is a match, and if there is do the replacement with the 5 groups and hyphens in between. If there is not match, return the original string.
The function stringToGUID() by itself does not do anything except log a string that is hardcoded in the function. To extend its functionality, you can pass a parameter.
function stringToGUID(s) {
const regex = /^([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/;
const m = s.replace(/-+/g, '').match(regex);
return m ? `${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}` : s;
}
[
'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
'b6b954d9-cbac-4b18-b0d5-a0f725695f1c',
'----54d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
'!##$%'
].forEach(s => {
console.log(stringToGUID(s));
});
Im trying to highlight some text on my web page as the user types in the search box. My search algo is simply matching each space separated keyword. I thought this function was perfect until I started adding brackets to my search term. That kicks up
SyntaxError: Invalid regular expression: ****: Unterminated group"
as its getting interpreted by the regex. Ive tried to escape the brackets and other characters but then the highlighting isn't working.
https://codepen.io/anon/pen/YOaYEv
highlight (str) {
// this line works but prevents highlighting multiple keywords that arent connected
// var replacedStr = (this.search || '').replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')
// you can comment this line and uncomment above to see a different but not perfect option
var replacedStr = (this.search || '').replace(/ /g, '|')
return str.replace(new RegExp(replacedStr, 'gi'), match => {
return '<span class="font-weight-bold">' + match + '</span>'
})
}
So i need to escape the brackets. Which ive tried in the commented line but then the function fails to highlight all keywords in the text :/
Any ideas?
You need to escape each non-whitespace chunk you want to search for and highlight. Also, there is no need to use a callback inside replace to replace with a whole match, you may use a $& backreference.
See the updated JS:
vm = new Vue({
el: "#app",
data() {
return {
search: null,
message: 'Search this text for matches (check the bracketed area too)'
};
},
computed: {},
methods: {
highlight (str) {
var replacedStr = (this.search || '').trim().split(/\s+/).map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')).join("|");
return str.replace(new RegExp(replacedStr, 'gi'),
'<span class="teal--text text--darken-1 font-weight-bold">$&</span>');
}
}
});
Here:
.trim().split(/\s+/).map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')).join("|") - trims the input string with trim(), then splits out all non-whitespace chunks with .split(/\s+/), then these chunks are escaped with .map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')), and then .join("|") creates a regex pattern with a list of alternatives.
In the '<span class="teal--text text--darken-1 font-weight-bold">$&</span>' string replacement pattern, the $& parts stands for the whole match value.
I want to add a Validation Rule to validate the Text either it should be any one of the following rules
Japanese character (Any Japanese letter) => 北海道
Alphabets (A-Z) => Kantname
Japanese character with Alphabets => 北海道AB
I written the below Regular Expression but its not working as expected
/^[a-zA-Z]+$|[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g;
If I tried the below its returning TRUE
console.log(pattern.test('北海道 <script>'));
You are using anchors in a wrong way: you need to merge all character classes into one single class and apply anchors to this superclass:
/^[a-zA-Z\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\u2605-\u2606\u2190-\u2195\u203B]+$/
See the regex demo
var re = /^[a-zA-Z\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\u2605-\u2606\u2190-\u2195\u203B]+$/;
var strs = ['北海道AB', 'Kantname', '北海道', '北海道 <script>'];
for (var s of strs) {
if (re.test(s)) {
console.log(s, " matches the regex");
} else {
console.log(s, " does NOT match the regex");
}
}
I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");
var input = [paul, Paula, george];
var newReg = \paula?\i
for(var text in input) {
if (newReg.test(text) == true) {
input[input.indexOf(text)] = george
}
}
console.log(input)
I don't know what's wrong in my code. it should change paul and Paula to george but when I run it it says there's an illegal character
The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
So, thats what is causing your error, you need to replace \paula?\i with /paula?/i
You need to replace \ by / in your regexp pattern.
You should wrap the strings inside quotes "
You need to match correctly your array, val is just the index of the word, not the word himself.
var input = ["paul", "Paula", "george"];
var newReg = /paula?/i;
for (var val in input) {
if (newReg.test(input[val]) == true) {
input[input.indexOf(input[val])] = "george";
}
}
console.log(input);
JSFIDDLE