Converting user input string to regular expression
Use the RegExp object constructor to create a regular expression from a string:
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
convert regex string to regex object in javascript
Two problems:
- You need to escape the backslash.
- You need to remove the forward slashes on the beginning and end of string.
Corrected code:
var pattern = "^[A-Za-z\\s]+$";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
http://jsfiddle.net/wn9scv3m/3/
How to convert a Java string against a pattern regex?
Try this method:
private static String formatVersion(String version) {
Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(-SNAPSHOT)*$");
Matcher matcher = pattern.matcher(version);
if (matcher.find()) {
return String.format("G%02dR%02dC%02d", Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3)));
} else {
throw new IllegalArgumentException("Unsupported version format");
}
}
Output for the version
param value 2.6.0
:
G02R06C00
convert string regex to regex with tag i
You need to extract the inner regex and flags before. Here's an example:
const path = "/v1/manager/notification/all"const regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"
const separator = regexPath.lastIndexOf('/')
const pattern = regexPath.slice(1, separator)const flags = regexPath.slice(separator + 1)
const regex = new RegExp(pattern, flags)
console.log('Pattern: ' + pattern)console.log('Flags: ' + flags)console.log('Regex: ' + regex)
convert string to regex pattern
You can puzzle this out:
- go over your strings characterwise
- if the character is a text character add a
't'
to a list - if the character is a number add a
'd'
to a list - if the character is something else, add itself to the list
- if the character is a text character add a
Use itertools.groupby
to group consecutive identical letters into groups.
Create a pattern from the group-key and the length of the group using some string literal formatting.
Code:
from itertools import groupby
from string import ascii_lowercase
lower_case = set(ascii_lowercase) # set for faster lookup
def find_regex(p):
cum = []
for c in p:
if c.isdigit():
cum.append("d")
elif c in lower_case:
cum.append("t")
else:
cum.append(c)
grp = groupby(cum)
return ''.join(f'\\{what}{{{how_many}}}'
if how_many>1 else f'\\{what}'
for what,how_many in ( (g[0],len(list(g[1]))) for g in grp))
pattern = "1example4...whatit.ry2do"
print(find_regex(pattern))
Output:
\d\t{7}\d\.{3}\t{6}\.\t{2}\d\t{2}
The ternary in the formatting removes not needed {1}
from the pattern.
See:
- str.isdigit()
If you now replace '\t'
with '[a-z]'
your regex should fit. You could also replace isdigit check using a regex r'\d'
or a in set(string.digits)
instead.
pattern = "1example4...whatit.ry2do"
pat = find_regex(pattern).replace(r"\t","[a-z]")
print(pat) # \d[a-z]{7}\d\.{3}[a-z]{6}\.[a-z]{2}\d[a-z]{2}
See
- string module for ascii_lowercase and digits
How to convert a regular expression to a String literal and back again?
Take a look at the accessor properties on the RegExp
prototype such as source
and flags
. So you can do:
var myRe = new RegExp("weather", "gi")
var copyRe = new RegExp(myRe.source, myRe.flags);
For the spec see http://www.ecma-international.org/ecma-262/6.0/#sec-get-regexp.prototype.flags.
Serializing and deserializing regexps
If your intent in doing this is to serialize the regexp, such as into JSON, and then deserialize it back, I would recommend storing the regexp as a tuple of [source, flags]
, and then reconstituting it using new RexExp(source, flags)
. That seems slightly cleaner than trying to pick it apart using regexp or eval'ing it. For instance, you could stringify it as
function stringifyWithRegexp(o) {
return JSON.stringify(o, function replacer(key, value) {
if (value instanceof RegExp) return [value.source, value.flags];
return value;
});
}
On the way back you can use JSON.parse
with a reviver to get back the regexp.
Modifying regexps
If you want to modify a regexp while retaining the flags, you can create a new regexp with modified source and the same flags:
var re = /weather/gim;
var newre = new RegExp(re.source + "| is", re.flags);
Convert string using regex in Java
Simply you can achieve it by regex
as follow if you want to just replace the long number:
String str2 = "/EMOTIONS_TAX/29027000/Points Of Interest/totem,"
+ "/EMOTIONS_TAX/29044000/Places/Italia,"
+ "/EMOTIONS_TAX/29027000/Military Equipment";
str2 = str2.replaceAll("\\d+", "22");
And the result will be:
/EMOTIONS_TAX/22/Points Of Interest/totem,/EMOTIONS_TAX/22/Places/Italia,/EMOTIONS_TAX/22/Military Equipment
UPDATED
As OP's request, OP tries to retrieve the number from the string instead actually and the solution should be:
String str2 = "/EMOTIONS_TAX/29027000/Points Of Interest/totem,"
+ "/EMOTIONS_TAX/29044000/Places/Italia,"
+ "/EMOTIONS_TAX/29027000/Military Equipment";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str2);
while(matcher.find()) {
System.out.println(matcher.group());
}
And the output:
29027000
29044000
29027000
Related Topics
How to Asynchronously Wait for X Seconds and Execute Something Then
Could Not Start Windows Service, Error 1064
Asp.Net Core, Change Default Redirect for Unauthorized
How to Call Wcf Service Method from Postman
Easiest Way to Check If an Arbitrary String Is a Valid Filename
C# Windows Form Application for Employee Management
How to Get a Specific Column Value from a Datatable
How to Set the Query Timeout from SQL Connection String
Create Global Variable in .Net Core 2.0 to Use in Razor Views
Call Method in Controller from View(Cshtml)
How to Round Up the Time to the Nearest X Minutes
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
How to Get Column Names of Table At Runtime in C#
Add Spaces Before Capital Letters
Cast Class into Another Class or Convert Class to Another
Javascript - How to Set Values to Session in JavaScript
How to Save Mailmessage Object to Disk as *.Eml or *.Msg File