Get text String in Between two Strings (keywords) - in Dart - Flutter - flutter

I'm currently using this function bellow to capture text after a certain keyword in a String of text :
static String? _getTextAfterKeyword({
required String inputtext,
required String keyword,
}) {
final indexKeyword = text.indexOf(keyword);
final indexAfter = indexKeyword + keyword.length;
if (indexKeyword == -1) {
return null;
} else {
return text.substring(indexAfter).trim();
}
}
Now I'm trying to capture a String of text in between two keywords - but what I've tried hasn't worked - 🙏
To illustrate this is what I need :
inputtext = "Lorem ipsum Lorem ipsum Lorem ipsum FIRSTKEYWORD - text I would like to return - SECONDKEYWORD Lorem ipsum Lorem ipsum Lorem ipsum"
the function would look something like this :
static String? _getTextInBetweenTwoKeywords({
required String inputtext,
required String firstKeyword,
required String SecondKeyword,
}) {
//Some Code
return the StringInBetweentheTwoKeywords;
}
``

Would something like this do the trick?
String capture(String first, String second, String input) {
int firstIndex = input.indexOf(first) + first.length;
int secondIndex = input.indexOf(second);
return input.substring(firstIndex, secondIndex);
}
void main() {
print(capture('FIRST', 'SECOND', 'AAAAAAA FIRST-what should print-SECOND BBBBBB')); // prints '-what should print-';
}

Related

Dart: give default value to empty or null string? How to do it with less code?

I have a Message object, with optional string title and required string message
I want to display the title, or if it's null or empty, display the message.
Since the title could be an empty string "", I can't just write msg.title ?? msg.message.
Now I'm writing it like this:
// the Message object
String? title;
String message;
// display
Text(msg.title?.isEmpty ?? true
? msg.message
: msg.title!)
This is ridiculously long and complicated. Is there a better way to do this?
Thanks everyone, I've learned a lot from your answers!<3
Seems like your Message class could be cooler. Here's a dartpad with my stuff.
class Message {
String? title;
String message; // could be better named - message property in a message class? Consider `details`
Message({required this.message, this.title});
/// Safe method to get displayed text for this [Message].
/// If the [title] is not null and is not empty, returns the title.
/// If the [title] is null or empty, returns the [message].
String get displayText {
return title == null || title!.isEmpty ? message : title!;
}
}
This would let you use message.displayText when you want to access the message.
// Some message
Message msg = Message(message: "Posted something successfully to the server", title: "Success!");
// The text widget
Text(msg.displayText);
add this extension to string:
extension on String? {
bool isNullEmpty => this == null && this.isEmpty;
}
and use it like this:
Text(msg.title.isNullEmpty ? msg.message: msg.title!)
I came up with this the other day, and will be doing a screencast for my YT channel soon (https://www.youtube.com/c/RandalLSchwartzonDartandFlutter). Here's the code:
void main(List<String> arguments) {
print('${Mine()}');
print('${Mine(name: 'Bob only')}');
print('${Mine(description: 'Guy only')}');
print('${Mine(name: 'Bob and', description: 'Guy')}');
print('${Mine(name: 'Bob', description: '')}');
print('${Mine(name: '', description: 'Guy')}');
print('${Mine(name: 'Bob', description: 'Guy')}');
}
extension IfEmptyOrNull on String? {
operator [](String value) {
if (this == null || this!.isEmpty) {
return value;
}
return this!;
}
}
class Mine {
final String name;
final String description;
Mine({String? name, String? description})
: name = name['No name'],
description = description['No description'];
#override
String toString() => 'Mine(name: $name, description: $description)';
}
The fun part is that someValue[theDefault] is just an array syntax, and even makes sense.

Extract template tags {{..}} from a string in flutter

I need to extract squiggly bracketed template tags from a string. For example:
String str="Hello {{user}}, your reference is {{ref}}"
I would like a to extract the tags in-between the {{..}} into an List. For example:
["user","ref"]
How can I do this, for example with a Regx - I would need to ignore any whitespace in-side the brackets for example {{ user}} would need to return "user".
This question is exactly same as this que.. Want code for flutter dart.
You can use this regex
void main() {
RegExp re = RegExp(r'{{([^]*?)}}');
String data = "Hello {{user}}, your reference is {{ref}}";
var match = re.firstMatch(data);
if (match != null) print(match.group(1));
List something = re.allMatches(data).map((m)=>m[1]).toList();
print(something);
}
OUtput
user
[user, ref]
void main() {
String str="Hello {{user}}, your reference is {{ref}}";
List<String> lstr = getStringBetweenBracket(str);
print(lstr);
}
List<String> getStringBetweenBracket(String str) {
List<String> rstr = [];
var j = str.splitMapJoin(new RegExp(r'\{\{(.*?)\}\}'), onMatch: (e) {
if( e.group(0) != null)
return e.group(0)!.replaceAll("{{","").replaceAll("}}","")+",";
else
return "";
}, onNonMatch: (e) { return ""; });
if(j != "") {
rstr = j.split(",");
rstr.removeAt(rstr.length-1);
}
return rstr;
}
you can do this way get array of data
void main() {
String str="Hello {{user}}, your reference is {{ref}}";
var parts = str.split(' ');
print(parts);
print(parts[1]);
}
void main(){
String str = 'HelloTutorialKart.';
int startIndex = 5;
int endIndex = 13;
//find substring
String result = str.substring(startIndex, endIndex);
print(result);
}
output
Tutorial

How to reverse only hebrew chars on a string dart?

I would like to reverse only hebrew chars in a string .
For example :
input: 1234 בלה בלה בלה
output': הלב הלב הלב 1234
Note that for the algorithm below to work you will need to manually add all the Hebrew characters to the list named chars I have only added the 3 Hebrew chars you specified in your example
Note that you could populate the char List using a json array if you can find one online. How to get json from the web
Create List of Hebrew characters
final List<String> chars = <String>[
"ב",
"ל",
"ה",
];
Create temp String from original string with only Hebrew characters, but in reverse
String temp = "";
for (int i = widget.reverseString.length - 1; i >= 0; i--) {
if (chars.contains(widget.reverseString[i])) {
temp += widget.reverseString[i];
}
}
Replace occurrences of Hebrew characters in original string with temp values
int tempIndex = 0;
String reveredString = widget.reverseString;
for (int r = 0; r < widget.reverseString.length; r++) {
if (chars.contains(widget.reverseString[r])) {
reveredString = _replaceCharAt(reveredString, r, temp[tempIndex]);
tempIndex++;
}
}
Full Example:
//ref:
//https://www.geeksforgeeks.org/reverse-a-string-without-affecting-special-characters/
import 'package:flutter/material.dart';
class ReverseHebrew extends StatefulWidget {
final String reverseString;
const ReverseHebrew({
Key? key,
required this.reverseString,
}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _ReverseHebrewState();
}
}
class _ReverseHebrewState extends State<ReverseHebrew> {
/*
This list must be manually populated to include all Hebrew characters for this
code to properly work.
*/
final List<String> chars = <String>[
"ב",
"ל",
"ה",
];
String _replaceCharAt(String oldString, int index, String newChar) {
return oldString.substring(0, index) +
newChar +
oldString.substring(index + 1);
}
String _reverse() {
// copy hebrew chars to temp in reverse order
String temp = "";
for (int i = widget.reverseString.length - 1; i >= 0; i--) {
if (chars.contains(widget.reverseString[i])) {
temp += widget.reverseString[i];
}
}
// replace occurrences of Hebrew chars in the original string with
// the reversed values in temp
int tempIndex = 0;
String reveredString = widget.reverseString;
for (int r = 0; r < widget.reverseString.length; r++) {
if (chars.contains(widget.reverseString[r])) {
reveredString = _replaceCharAt(reveredString, r, temp[tempIndex]);
tempIndex++;
}
}
// return reversed string
return reveredString;
}
#override
Widget build(BuildContext context) {
return Text(_reverse());
}
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: Column(
children: [
Text("Original: 1234 בלה בלה בלה"),
Text("Reversed:"),
ReverseHebrew(
reverseString: "בלה בלה בלה 1234",
),
],
),
),
),
),
);
}
Ref: Geeks for Geeks Algorithm
Seemingly Hebrew has the range \u0590-\u05fe (according to this nice JavaScript Unicode Regex generator).
So we can use this to find and reverse Hebrew only from any given string.
Here is the perfect working example:
String reverseHebrew(String text) {
text = text.splitMapJoin(
RegExp(r'[\u0590-\u05FF]+'),
onMatch: (m) => m.group(0).split('').reversed.join(),
onNonMatch: (string) => string,
);
// reverse words in string
return text.split(' ').reversed.join(' ');
}

How to replace n occurrence of a substring in a string in dart?

I want to replace n occurrence of a substring in a string.
myString = "I have a mobile. I have a cat.";
How I can replace the second have of myString
hope this simple function helps. You can also extract the function contents if you don't wish a function. It's just two lines with some
Dart magic
void main() {
String myString = 'I have a mobile. I have a cat.';
String searchFor='have';
int replaceOn = 2;
String replaceText = 'newhave';
String result = customReplace(myString,searchFor,replaceOn,replaceText);
print(result);
}
String customReplace(String text,String searchText, int replaceOn, String replaceText){
Match result = searchText.allMatches(text).elementAt(replaceOn - 1);
return text.replaceRange(result.start,result.end,replaceText);
}
Something like that should work:
String replaceNthOccurrence(String input, int n, String from, String to) {
var index = -1;
while (--n >= 0) {
index = input.indexOf(from, ++index);
if (index == -1) {
break;
}
}
if (index != -1) {
var result = input.replaceFirst(from, to, index);
return result;
}
return input;
}
void main() {
var myString = "I have a mobile. I have a cat.";
var replacedString = replaceNthOccurrence(myString, 2, "have", "had");
print(replacedString); // prints "I have a mobile. I had a cat."
}
This would be a better solution to undertake as it check the fallbacks also. Let me list down all the scenarios:
If position is 0 then it will replace all occurrence.
If position is correct then it will replace at same location.
If position is wrong then it will send back input string.
If substring does not exist in input then it will send back input string.
void main() {
String input = "I have a mobile. I have a cat.";
print(replacenth(input, 'have', 'need', 1));
}
/// Computes the nth string replace.
String replacenth(String input, String substr, String replstr,int position) {
if(input.contains(substr))
{
var splittedStr = input.split(substr);
if(splittedStr.length == 0)
return input;
String finalStr = "";
for(int i = 0; i < splittedStr.length; i++)
{
finalStr += splittedStr[i];
if(i == (position - 1))
finalStr += replstr;
else if(i < (splittedStr.length - 1))
finalStr += substr;
}
return finalStr;
}
return input;
}
let's try with this
void main() {
var myString = "I have a mobile. I have a cat.I have a cat";
print(replaceInNthOccurrence(myString, "have", "test", 1));
}
String replaceInNthOccurrence(
String stringToChange, String searchingWord, String replacingWord, int n) {
if(n==1){
return stringToChange.replaceFirst(searchingWord, replacingWord);
}
final String separator = "#######";
String splittingString =
stringToChange.replaceAll(searchingWord, separator + searchingWord);
var splitArray = splittingString.split(separator);
print(splitArray);
String result = "";
for (int i = 0; i < splitArray.length; i++) {
if (i % n == 0) {
splitArray[i] = splitArray[i].replaceAll(searchingWord, replacingWord);
}
result += splitArray[i];
}
return result;
}
here the regex
void main() {
var myString = "I have a mobile. I have a cat. I have a cat. I have a cat.";
final newString =
myString.replaceAllMapped(new RegExp(r'^(.*?(have.*?){3})have'), (match) {
return '${match.group(1)}';
});
print(newString.replaceAll(" "," had "));
}
Demo link
Here it is one more variant which allows to replace any occurrence in subject string.
void main() {
const subject = 'I have a dog. I have a cat. I have a bird.';
final result = replaceStringByOccurrence(subject, 'have', '*have no*', 0);
print(result);
}
/// Looks for `occurrence` of `search` in `subject` and replace it with `replace`.
///
/// The occurrence index is started from 0.
String replaceStringByOccurrence(
String subject, String search, String replace, int occurence) {
if (occurence.isNegative) {
throw ArgumentError.value(occurence, 'occurrence', 'Cannot be negative');
}
final regex = RegExp(r'have');
final matches = regex.allMatches(subject);
if (occurence >= matches.length) {
throw IndexError(occurence, matches, 'occurrence',
'Cannot be more than count of matches');
}
int index = -1;
return subject.replaceAllMapped(regex, (match) {
index += 1;
return index == occurence ? replace : match.group(0)!;
});
}
Tested on dartpad.

TextAllCaps in Text() widget of Flutter?

As we are having android:textAllCaps="true" feature in Android's Textview, how can we give this same feature in Text() Widget of Flutter?
I know Text('Abc'.toUpperCase()), is one way but I don't want to do it manually. Is there any property of Text() widget that converts it automatically or any widget that has similar property?
(EDITED) My solution is like this:
Text("apple".toUpperCase())
Returns:
APPLE
Use following function for the First word as Caps
String getCapitalizeString({String str}) {
if (str.length <= 1) { return str.toUpperCase(); }
return '${str[0].toUpperCase()}${str.substring(1)}';
}
Use :
Text(this.getCapitalizeString(str: listObj[position]);
To capitalize the text like this: "this is only a example" to this "This Is Only A Example",
use this function:
firstCharacterUpper(String text) {
List arrayPieces = List();
String outPut = '';
text = 'this is only a example'; // This is not necessary, is only for the example. The text here is that one is passed in parameter.
text.split(' ').forEach((sepparetedWord) {
arrayPieces.add(sepparetedWord);
});
arrayPieces.forEach((word) {
word =
"${word[0].toString().toUpperCase()}${word.toString().substring(1)} ";
outPut += word;
});
return outPut;
}
OutPut: 'This Is Only A Example'.
just to simplify the function of the answers before
String getCapitalizeString(String str) {
String cRet = '';
str.split(' ').forEach((word) {
cRet += "${word[0].toUpperCase()}${word.substring(1).toLowerCase()} ";
});
return cRet.trim();
}