I fetched data from a web sites body.Then I write a regular expression and applied on DART but it didnt work.What is the Problem?
Here is the Regex code:
</td><td align="left">(.*?)</td><td class="dataGridActive
Here is my part of the content:
</tr><tr onmouseover="mover(this);" onmouseout="mout(this);" style="background-color:White;">
<td align="left">233</td><td align="left">ÖMER EFE CIKIT</td><td class="dataGridActive" align="center">
And the dart code:
void CheckRE(String text) {
final RegExp pattern = RegExp(
r'</td><td align="left">(.*?)</td><td class="dataGridActive"',
multiLine: true,
caseSensitive: true,
); // 800 is the size of each chun
pattern
.allMatches(text)
.forEach((RegExpMatch match) => print(match.group(1)));
}
I think what you want is the following.
I have changed your output so it prints the content of capture group 1 instead of capture group 0. Capture group 0 contains the whole string which matches while 1 and up contains the content of each defined capture group in your regular expression.
const input = '''
</tr><tr onmouseover="mover(this);" onmouseout="mout(this);" style="background-color:White;">
<td align="left">233</td><td align="left">ÖMER EFE CIKIT</td><td class="dataGridActive" align="center">
''';
void main() => checkRE(input); // ÖMER EFE CIKIT
void checkRE(String text) {
final RegExp pattern = RegExp(
r'</td><td align="left">(.*?)</td><td class="dataGridActive"',
multiLine: true,
caseSensitive: true,
); // 800 is the size of each chun
pattern.allMatches(text).forEach((RegExpMatch match) => print(match[1]));
}
Also changed (.*) to (.*?) based on advice from #MikeM.
Related
I would like to assert in Protractor that a link text is composed by the following way: text-1 (where text is a variable, and the number can be composed by any digits).
I tried the following:
browser.wait(
ExpectedConditions.visibilityOf(
element(by.xpath(`//a[#class = 'collapsed' and starts-with(text(), '${text}') and ends-with(text(), '-(/d+)')]`))),
5000)
and
browser.wait(
ExpectedConditions.visibilityOf(
element(by.xpath(`//a[#class = 'collapsed' and starts-with(text(), '${text}') and ends-with(text(), '/^-(/d+)$/')]`))),
5000)
Unfortunately, none of the above xpaths worked.
How can I fix this?
If you change the way to declare the variable and your second predicate you can go with :
//a[#class='collapsed'][starts-with(text(),'" + text_variable + "')][number(replace(.,'^.*-(\d+)$','$1'))*0=0]
where [number(replace(.,'^.*-(\d+)$','$1'))*0=0] test for the presence of a number at the end of a string.
Example. If you have :
<p>
<a class="collapsed">foofighters-200</a>
<a class="collapsed">foofighters</a>
<a class="collapsed">boofighters-200</a>
<a class="collapsed">boofighters-200abc</a>
</p>
The following XPath :
//a[#class='collapsed'][starts-with(text(),'foo')][number(replace(.,'^.*-(\d+)$','$1'))*0=0]
will output 1 element :
<a class="collapsed">foofighters-200</a>
So in Protractor you could have :
var text = "foo";
browser.wait(ExpectedConditions.visibilityOf(element(by.xpath("//a[#class='collapsed'][starts-with(text(),'" + text + "')][number(replace(.,'^.*-(\d+)$','$1'))*0=0]"))), 5000);
...
You can use regexp for this:
await browser.wait(async () => {
return new RegExp('^.*(\d+)').test(await $('a.collapsed').getText());
}, 20000, 'Expected link text to contain number at the end');
Tune this regex here if needed:
https://regex101.com/r/9d9yaJ/1
I'm filtering list like this but i think there should be better approach to filter list inside where bloc it is not allowing me to declare variable. is there any other way to achieve the same
var cc = contactsAll
.where(
(i) =>
regularExpression(i.displayName, 'dev') ||
regularExpression(i.displayName, 'soft') ||
regularExpression(i.displayName, 'angular') ||
regularExpression(i.displayName, 'java')
)
.toList();
my expression filter function
bool regularExpression(String stringg, String search) {
RegExp exp = new RegExp(
"\\b" + search + "\\b",
caseSensitive: false,
);
return exp.hasMatch(stringg);
}
Thanks in advance
You may build the pattern dynamically:
var keys = ['dev', 'soft', 'angular', 'java'];
var regex = new RegExp("\\b(?:${keys.join('|')})\\b", caseSensitive: false);
var contactsAll = ['No match', 'I like java', 'I like javascript'];
var cc = contactsAll.where( (i) => regex.hasMatch(i) ).toList();
print(cc); // => [I like java]
The regex will look like \b(?:dev|soft|angular|java)\b and will match any of the keywords inside the non-capturing group as a whole word due to the \b word boundaries. See the regex demo.
If the keys can contain special characters, but you still need a whole word search, you need to escape all special characters and use either unambiguous boundaries
var regex = new RegExp("(?:^|\\W)(?:${keys.map((val) => val.replaceAll(new RegExp(r'[-\/\\^$*+?.()|[\]{}]'), r'\\$&')).join('|')})(?!\\w)", caseSensitive: false);
This results in a (?:^|\W)(?:dev|soft|angular|java)(?!\w) pattern (see demo) where (?:^|\W) matches start of string or a non-word char and (?!\w) requires the absense of a word char immediately to the right of the current location.
The .map((val) => val.replaceAll(new RegExp(r'[-\/\\^$*+?.()|[\]{}]'), r'\\$&')) part escapes the literal part for use within regex.
Or whitespace boundaries:
var regex = new RegExp("(?:^|\\s)(?:${keys.map((val) => val.replaceAll(new RegExp(r'[-\/\\^$*+?.()|[\]{}]'), r'\\$&')).join('|')})(?!\\S)", caseSensitive: false);
This results in a (?:^|\s)(?:dev|soft|angular|java)(?!\S) pattern where (?:^|\s) matches start of string or a whitespace char and (?!\S) requires the absense of a non-whitespace char immediately to the right of the current location.
See the regex demo.
Without creating a function, you can use the contains method on your displayName like this :
var cc = contactsAll
.where((i) =>
i.displayName.contains(RegExp('\\bdev\\b')) ||
i.displayName.contains(RegExp('\\bsoft\\b')) ||
i.displayName.contains(RegExp('\\bangular\\b')) ||
i.displayName.contains(RegExp('\\bjava\\b')),)
.toList();
I used this snippet to make line breaks inside text. how can I delete the text behind the nth whitespace completely?
var str:String = ("This is just a test string").replace(/(( [^ ]+){2}) /, "$1\n");
regards
This works using regex (([^ ]* ){2}).* and replace pattern $1:
function removeAfterNthSpace() {
var nth = parseInt($("#num").val());
var regEx = new RegExp("(([^ ]* ){" + nth + "}).*", "g")
var str = ("This is just a test string").replace(regEx, "$1");
console.log(str);
}
$('#num').change(removeAfterNthSpace);
removeAfterNthSpace();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="num" value="2" />
See it working on regex101.
In a Flutter application, I need to check if a string matches a specific RegEx. However, the RegEx I copied from the JavaScript version of the app always returns false in the Flutter app. I verified on regexr that the RegEx is valid, and this very RegEx is already being used in the JavaScript application, so it should be correct.
Any help is appreciated!
RegEx : /^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i
Test Code :
RegExp regExp = new RegExp(
r"/^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i",
caseSensitive: false,
multiLine: false,
);
print("allMatches : "+regExp.allMatches("WS://127.0.0.1:56789").toString());
print("firstMatch : "+regExp.firstMatch("WS://127.0.0.1:56789").toString());
print("hasMatch : "+regExp.hasMatch("WS://127.0.0.1:56789").toString());
print("stringMatch : "+regExp.stringMatch("WS://127.0.0.1:56789").toString());
Output :
allMatches : ()
firstMatch : null
hasMatch : false
stringMatch : null
This is a more general answer for future viewers.
Regex in Dart works much like other languages. You use the RegExp class to define a matching pattern. Then use hasMatch() to test the pattern on a string.
Examples
Alphanumeric
final alphanumeric = RegExp(r'^[a-zA-Z0-9]+$');
alphanumeric.hasMatch('abc123'); // true
alphanumeric.hasMatch('abc123%'); // false
Hex colors
RegExp hexColor = RegExp(r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');
hexColor.hasMatch('#3b5'); // true
hexColor.hasMatch('#FF7723'); // true
hexColor.hasMatch('#000000z'); // false
Extracting text
final myString = '25F8..25FF ; Common # Sm [8] UPPER LEFT TRIANGLE';
// find a variable length hex value at the beginning of the line
final regexp = RegExp(r'^[0-9a-fA-F]+');
// find the first match though you could also do `allMatches`
final match = regexp.firstMatch(myString);
// group(0) is the full matched text
// if your regex had groups (using parentheses) then you could get the
// text from them by using group(1), group(2), etc.
final matchedText = match?.group(0); // 25F8
There are some more examples here.
See also:
Extracting text from a string with regex groups in Dart
I think you tried to include options in the raw expression string while you already have it as parameters to RegEx ( /i for case insensitivity is declared as caseSensitive: false).
// Removed /i at the end
// Removed / in front - Thanks to Günter for warning
RegExp regExp = new RegExp(
r"^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789",
caseSensitive: false,
multiLine: false,
);
print("allMatches : "+regExp.allMatches("WS://127.0.0.1:56789").toString());
print("firstMatch : "+regExp.firstMatch("WS://127.0.0.1:56789").toString());
print("hasMatch : "+regExp.hasMatch("WS://127.0.0.1:56789").toString());
print("stringMatch : "+regExp.stringMatch("WS://127.0.0.1:56789").toString());
Gives:
allMatches : (Instance of '_MatchImplementation')
firstMatch : Instance of '_MatchImplementation'
hasMatch : true
stringMatch : WS://127.0.0.1:56789
There is a string in the following format:
It can start with any number of strings enclosed by double braces, possibly with white space between them (whitespace may or may not occur).
It may also contain strings enclosed by double-braces in the middle.
I am looking for a regular expression that can separate the start from the rest.
For example, given the following string:
{{a}}{{b}} {{c}} def{{g}}hij
The two parts are:
{{a}}{{b}} {{c}}
def{{g}}hij
I tried this:
/^({{.*}})(.*)$/
But, it captured also the g in the middle:
{{a}}{{b}} {{c}} def{{g}}
hij
I tried this:
/^({{.*?}})(.*)$/
But, it captured only the first a:
{{a}}
{{b}} {{c}} def{{g}}hij
This keeps matching {{, any non { or } character 1 or more times, }}, possible whitespace zero or more times and stores it in the first group. Rest of the string will be in the 2nd group. If there are no parts surrounded by {{ and }} the first group will be empty. This was in JavaScript.
var str = "{{a}}{{b}} {{c}} def{{g}}hij";
str.match(/^\s*((?:\{\{[^{}]+\}\}\s*)*)(.*)/)
// [whole match, group 1, group 2]
// ["{{a}}{{b}} {{c}} def{{g}}hij", "{{a}}{{b}} {{c}} ", "def{{g}}hij"]
How about using preg_split:
$str = '{{a}}{{b}} {{c}} def{{g}}hij';
$list = preg_split('/(\s[^{].+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($list);
output:
Array
(
[0] => {{a}}{{b}} {{c}}
[1] => def{{g}}hij
)
I think I got it:
var string = "{{a}}{{b}} {{c}} def{{g}}hij";
console.log(string.match(/((\{\{\w+\}\})\s*)+/g));
// Output: [ '{{a}}{{b}} {{c}} ', '{{g}}' ]
Explanation:
( starts a group.
( another;
\{\{\w+\}\} looks for {{A-Za-z_0-9}}
) closes second group.
\s* Counts whitespace if it's there.
)+ closes the first group and looks for oits one or more occurrences.
When it gets any not-{{something}} type data, it stops.
P.S. -> Complex RegEx takes CPU speed.
You can use this:
(java)
string[] result = yourstr.split("\\s+(?!{)");
(php)
$result = preg_split('/\s+(?!{)/', '{{a}}{{b}} {{c}} def{{g}}hij');
print_r($result);
I don´t know exactly why are you want to split, but in case that the string contains always a def inside, and you want to separate the string from there in two halves, then, you can try something like:
string text = "{{a}}{{b}} {{c}} def{{g}}hij";
Regex r = new Regex("def");
string[] split = new string[2];
int index = r.Match(text).Index;
split[0] = string.Join("", text.Take(index).Select(x => x.ToString()).ToArray<string>());
split[1] = string.Join("", text.Skip(index).Take(text.Length - index).Select(x => x.ToString()).ToArray<string>());
// Output: [ '{{a}}{{b}} {{c}} ', 'def{{g}}hij' ]