Reputation: 551
How can I find any word from beginning of string to first char "~" using java?
Example:
Worddjjfdskfjsdkfjdsj ~ Word ~ Word
I want it to capture
Worddjjfdskfjsdkfjdsj
Upvotes: 0
Views: 365
Reputation: 736
You can also do it without regex in a very simple way. First of all use indexOf() String method to find the index of the "~" character. Then use the substring() method to extract the string you are lookin for. Here is an example:
String stringToProcess = "hello~world";
int charIndex = stringToProcess.indexOf('~');
String finalString = stringToProcess.substring(0, charIndex);
Upvotes: 1
Reputation: 115328
Here is regular expression that you can use: ^(.*?)~
.
However in your simple case you do not need regular expressions at all. Use indexOf()
and substring()
:
int tilda = str.indexOf('~');
if (tilda >= 0) {
word = str.substring(0, tilda);
}
Upvotes: 0
Reputation: 4534
Without regex it can be solved
Simply split your string by ~
.
String str[] = "Worddjjfdskfjsdkfjdsj ~ Word ~ Word".split("~");
System.out.println(str[0]);
Upvotes: 0
Reputation: 784958
You can use this regex to capture all character from start of string ^
to first occurrence of ~
:
^[^~]*
[^~]*
is negation based regex that matches 0 or more of anything but ~
Upvotes: 0